且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Qt表格小部件,删除行的按钮

更新时间:2023-11-14 16:50:04

要删除行,我们必须先获取行,如果我们在单元格内插入小部件,currentRow() 方法将不会返回适当的行,在很多情况下,它会返回最后一个没有被选中的小部件的单元格的行.

To remove the row we must first get the row, if we are inserting widgets inside the cells the currentRow() method will not return the appropriate row, in many cases it will return the row of the last cell without widget that has been selected.

出于这个原因,您必须选择其他解决方案,对于这种情况,我们将使用 QTableWidgetindexAt() 方法,但为此我们需要知道位置以单元格的像素为单位.当一个小部件添加到一个单元格时,这个单元格将成为小部件的父级,因此我们可以使用 parent() 方法从按钮访问单元格,然后获取该小部件的位置单元格相对于 QTableWidget 并在 indexAt() 中使用它.要访问按钮,我们将使用 sender().

For that reason you must opt for another solution, for this case we will use the indexAt() method of QTableWidget, but for this we need to know the position in pixels of the cell. when one adds a widget to a cell, this cell will be the parent of the widget, so we can access from the button to the cell using the parent() method, and then get the position of the cell with respect to the QTableWidget and use it in indexAt(). To access the button we will use the sender().

当当前单元格被移除时,焦点会丢失,一个可能的解决方案是将焦点再次放在另一个单元格中.

When the current cell is removed the focus is lost, a possible solution is to place the focus again in another cell.

void MainWindow::deleteThisLine()
{
    //sender(): QPushButton
    QWidget *w = qobject_cast<QWidget *>(sender()->parent());
    if(w){
        int row = ui->tableWidget->indexAt(w->pos()).row();
        ui->tableWidget->removeRow(row);
        ui->tableWidget->setCurrentCell(0, 0);
    }
}