Qt篇——QTableWidget选中多行右键删除

02-29 1175阅读

效果如图:

Qt篇——QTableWidget选中多行右键删除

代码如下:

头文件中:

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 originDataTable->removeRow(deleteItem -  i);
        }
    }
}
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]