从相应行的按钮中检索tableWidget行

Retrieve tableWidget row from button in corresponding row

本文关键字:检索 tableWidget 按钮      更新时间:2023-10-16

我有一个tableWidget,我使用为其动态创建行

ui.tableWidget->insertRow(0);
QTableWidgetItem *newItemText = new QTableWidgetItem("bla", 0);
QPushButton *goButton = new QPushButton("Go", ui.tableWidget);
connect(goButton, SIGNAL(clicked()), this, SLOT(on_pushButtonGo_clicked_custom() ));
ui.tableWidget->setItem(0, 0, newItemText);
ui.tableWidget->setCellWidget(0, 1, goButton);

在每一行中,我都有一个单元格"Go"和一个包含按钮的单元格。这些按钮都连接到插槽on_pushButtonGo_clicked_custom。

现在,在on_pushButtonGo_clicked_custom中,我需要检索相应的行,在该行中单击了按钮。我该怎么做?

非常感谢你的帮助!

QSignalMapper允许将字符串或整数与原始信号对象相关联。这意味着您可以将每个goButton与相应的行相关联。文档中的示例看起来与您的问题有关。

你需要修改你的代码像这样:

...
#include <QSignalMapper>
...
QSignalMapper * signalMapper = new QSignalMapper (this);
ui.tableWidget->insertRow(0);
QTableWidgetItem *newItemText = new QTableWidgetItem("bla", 0);
QPushButton *goButton = new QPushButton("Go", ui.tableWidget);
signalMapper->setMapping (goButton, 0); // where 0 is row number.
connect(goButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
// You need rewrite slot for passing number of row.
connect(signalMapper, SIGNAL(mapped(const int)), this, SLOT(on_pushButtonGo_clicked_custom(const int)));
ui.tableWidget->setItem(0, 0, newItemText);
ui.tableWidget->setCellWidget(0, 1, goButton);

行数将通过on_pushButtonGo_clicked_custom(const int)插槽的参数可用:

...
void MainWidget::on_pushButtonGo_clicked_custom(const int rowNumber)
{
    qDebug () << "Row number is: " << rowNumber;
}