Qt表格小部件,删除行的按钮 [英] Qt table widget, button to delete row

查看:70
本文介绍了Qt表格小部件,删除行的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QTableWidget 并且对于所有行,我将一列的 setCellWidget 设置为一个按钮.

I have a QTableWidget and for all rows I set a setCellWidget at one column to a button.

我想将此按钮连接到删除该行的函数.我尝试了这段代码,但它不起作用,因为如果我只是单击我的按钮,我不会将当前行设置为按钮所在的行.

I would like to connect this button to a function that delets this row. I tried this code, which does not work, because if I simply click my button I do not set the current row to the row of the button.

ui->tableWidget->insertRow(ui->tableWidget->rowCount());
QPushButton *b = new QPushButton("delete",this);
ui->tableWidget->setCellWidget(ui->tableWidget->rowCount()-1,0,b);
connect(d,SIGNAL(clicked(bool)),this,SLOT(deleteThisLine()));
...


void MainWindow::deleteThisLine()
{
    int row = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(row);
}

如何将我的按钮连接到一个函数,让函数知道按下了哪个按钮(在哪一行)?

How can I connect my button to a function in a way that the function knows which button (at which row) was pressed?

推荐答案

要删除行,我们必须先获取行,如果我们在单元格内插入小部件,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);
    }
}

这篇关于Qt表格小部件,删除行的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆