使用QT 写个qtableWidget 选择某片区域右键复制黏贴的程序
时间: 2024-03-10 13:44:18 浏览: 75
好的,以下是一个使用Qt编写的QTableWidget右键菜单实现复制和粘贴的程序示例:
```cpp
// 定义QTableWidget
QTableWidget *tableWidget = new QTableWidget(parent);
tableWidget->setRowCount(5);
tableWidget->setColumnCount(5);
// 定义右键菜单
QMenu *menu = new QMenu(tableWidget);
QAction *copyAction = new QAction("复制", menu);
QAction *pasteAction = new QAction("粘贴", menu);
// 添加菜单项
menu->addAction(copyAction);
menu->addAction(pasteAction);
// 右键菜单信号槽连接
connect(tableWidget, &QTableWidget::customContextMenuRequested, [=](const QPoint &pos) {
menu->exec(tableWidget->viewport()->mapToGlobal(pos));
});
// 复制操作信号槽连接
connect(copyAction, &QAction::triggered, [=]() {
// 获取选中区域
QTableWidgetItem *item;
QModelIndexList indexes = tableWidget->selectionModel()->selectedIndexes();
if (indexes.isEmpty()) {
return;
}
// 复制选中区域
QString text;
int previousRow = -1;
foreach (QModelIndex index, indexes) {
int row = index.row();
int column = index.column();
if (row != previousRow) {
previousRow = row;
text += "\n";
} else {
text += "\t";
}
item = tableWidget->item(row, column);
if (item) {
text += item->text();
}
}
// 将复制内容写入剪贴板
QApplication::clipboard()->setText(text);
});
// 粘贴操作信号槽连接
connect(pasteAction, &QAction::triggered, [=]() {
// 获取剪贴板内容
QString text = QApplication::clipboard()->text();
QStringList rows = text.split("\n", QString::SkipEmptyParts);
if (rows.isEmpty()) {
return;
}
// 获取当前选中的单元格
QTableWidgetItem *currentItem = tableWidget->currentItem();
int currentRow = -1;
if (currentItem) {
currentRow = currentItem->row();
}
// 粘贴内容
int row = 0;
int column = 0;
foreach (QString rowText, rows) {
QStringList columns = rowText.split("\t", QString::SkipEmptyParts);
foreach (QString columnText, columns) {
if (currentRow >= 0 && row == 0) {
// 将第一行粘贴到当前选中单元格所在行
tableWidget->setItem(currentRow, column, new QTableWidgetItem(columnText));
} else {
// 将其他行追加到表格末尾
if (row >= tableWidget->rowCount()) {
tableWidget->setRowCount(row + 1);
}
tableWidget->setItem(row, column, new QTableWidgetItem(columnText));
}
column++;
}
row++;
column = 0;
}
});
```
该程序实现了在QTableWidget中选中区域,并通过右键菜单实现复制和粘贴功能。注意,该程序只是一个示例,你需要根据你的实际需求进行修改和完善。
阅读全文