源码如下:
头文件
源文件:
void frmDbDelegate::initTableView() { m_pActionCopy = new QAction(tr("复制"), ui->tableView); connect(m_pActionCopy, &QAction::triggered, this, &frmDbDelegate::copyData2); ui->tableView->setSelectionMode(QAbstractItemView::ContiguousSelection); //设置为连续选择模式 ui->tableView->setContextMenuPolicy(Qt::ActionsContextMenu); //设置为action菜单模式 ui->tableView->addAction(this->m_pActionCopy); } //粘贴板表格内容格式: //列与列之间内容以制表符分隔("\t") //行与行之间内容以换行符分隔("\n") //粘贴: //获取粘贴板内容,把内容分解成单个item的值并放到表格中 //通过QApplication::clipboard()->text()类获取粘贴板的内容 //复制: //获取选中item,把选中item内容组织一下并放到粘贴板 //通过QApplication::clipboard()->setText()设置粘贴板内容 void frmDbDelegate::copyData1() { QModelIndexList indexes = ui->tableView->selectionModel()->selectedIndexes(); if (indexes.count() == 0) { //select nothing return; } QMap<QString, QString> map; QModelIndex index; int k = 0; int maxCol = 0; int maxRow = 0; int minCol = 0; int minRow = 0; foreach (index, indexes) { int col = index.column(); int row = index.row(); if (k == 0) { minCol = col; minRow = row; } if (col > maxCol) maxCol = col; if (row > maxRow) maxRow = row; QString text = index.model()->data(index, Qt::EditRole).toString(); map[QString::number(row) + "," + QString::number(col)] = text; k++; } QString rs = ""; for (int row = minRow; row <= maxRow; row++) { for (int col = minCol; col <= maxCol; col++) { if (col != minCol) rs += "\t"; rs += map[QString::number(row) + "," + QString::number(col)]; } } rs += "\r\n"; //复制到剪贴板 QClipboard *board = QApplication::clipboard(); board->setText(rs); qDebug() << rs; } void frmDbDelegate::copyData2() { QStringList list; QModelIndexList indexes = ui->tableView->selectionModel()->selectedIndexes(); if (indexes.count() == 0) { //select nothing return; } foreach (const QModelIndex &index, indexes) { list << index.data().toString(); } QApplication::clipboard()->setText(list.join(",")); }
---
参考文献
《Qt QTableView 上加右键弹出菜单, 并复制选中的单元格内容到剪贴板中》
http://www.doczj.com/doc/c51cfb63cf84b9d528ea7a29.html
《已选中QTableView中的行/行复制到QClipboard》
http://cn.voidcc.com/question/p-myqnyjft-mk.html
《复制QTableView的一部分(Copying part of QTableView)》
https://www.it1352.com/549965.html
《QTableWidget, QTableView实现粘贴复制》
https://blog.csdn.net/time_forget/article/details/100765595