源碼如下:
頭檔案
private:
QAction *m_pActionCopy;
private slots:
void copyData1();
void copyData2();
源檔案:
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