Qt create 给table widget 表头填加右键槽函数在槽函数中将整列数据提出到一个stringlist 变量
时间: 2024-02-20 13:56:47 浏览: 135
可以通过以下步骤实现:
1. 为表头添加右键菜单:
```cpp
QMenu *menu = new QMenu(ui->tableWidget);
ui->tableWidget->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->tableWidget->horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showHeaderContextMenu(QPoint)));
```
2. 在槽函数`showHeaderContextMenu`中实现菜单的响应,并将选中列的数据提取到一个`QStringList`变量中:
```cpp
void MainWindow::showHeaderContextMenu(const QPoint &pos) {
QMenu *menu = new QMenu(ui->tableWidget);
QAction *action = new QAction("Export Column Data", this);
connect(action, &QAction::triggered, this, [=]() {
QItemSelectionModel *selectionModel = ui->tableWidget->selectionModel();
QModelIndexList selectedColumns = selectionModel->selectedColumns();
QStringList columnData;
foreach (QModelIndex index, selectedColumns) {
int col = index.column();
for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
columnData.append(ui->tableWidget->item(row, col)->text());
}
}
qDebug() << columnData;
});
menu->addAction(action);
menu->popup(ui->tableWidget->horizontalHeader()->viewport()->mapToGlobal(pos));
}
```
在上述代码中,我们首先获取选中的列的索引列表,然后遍历每一列,将每一行中该列的数据提取出来并添加到`columnData`变量中,最后输出`columnData`变量的内容。
阅读全文