效果如图:
代码如下:
头文件中:
QTableWidgetItem *selectedItem; //表格被选中的一行
QMenu* originDataTableContextMenu; //表格右键菜单
QAction* originDataTableActionDel; //表格右键菜单的删除项
cpp文件中:
void MainWindow::initTable() {//设置点击时选中一整行ui->originDataTable->setSelectionBehavior(QAbstractItemView::SelectRows);//添加表格右键菜单ui->originDataTable->setContextMenuPolicy(Qt::CustomContextMenu);originDataTableContextMenu = new QMenu(this);originDataTableActionDel = new QAction(this);originDataTableActionDel->setText(QString("删除"));originDataTableContextMenu->addAction(originDataTableActionDel);//表格右键菜单项的信号槽连接connect(originDataTableContextMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotMenuClicked(QAction*)));connect(ui->originDataTable, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(tableContexMenuRequested(const QPoint&)));
}//槽函数void MainWindow::tableContexMenuRequested(const QPoint &pos) {selectedItem = ui->originDataTable->itemAt(pos);if(selectedItem != nullptr) {originDataTableContextMenu->exec(QCursor::pos());}
}void MainWindow::slotMenuClicked(QAction *act) {if (act == originDataTableActionDel) {QModelIndexList items = ui->originDataTable->selectionModel()->selectedRows();//先将选中的项进行排序, 再依次从表格数据中删除选中的项sort(items.begin(), items.end());for (int i = 0; i < items.size(); i++) {int deleteItem = items[i].row();//减i是因为每删掉一个前面的元素, 删后面的元素长度都需要减去已删除的元素个数ui->originDataTable->removeRow(deleteItem - i);}}
}