效果如图:

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

代码如下:

头文件中:

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);
        }
    }
}
03-03 22:17