2014-09-03 26 views
1

我有一個tableWidget,爲此,我使用從按鈕檢索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); 

在每一行中我有一個細胞「轉到」和包含一個按鈕的小區動態地創建行。這些按鈕全部連接到插槽on_pushButtonGo_clicked_custom。

現在在on_pushButtonGo_clicked_custom中,我需要檢索相應的行,其中按鈕被點擊。我怎樣才能做到這一點?

非常感謝您的幫助!

回答

1

QSignalMapper允許將原始信號對象與字符串或整數關聯。這意味着您可以將每個goButton與相應的行相關聯。 Example in documentation看起來與你的問題有關。

你需要修改你的代碼是這樣的:

... 
#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; 
} 
+0

謝謝@Gluttton 我修改了插槽功能「on_pushButtonGo_clicked_custom (const int)「。 如何在這裏檢索映射的整數(0)? const int後不應該有一個參數名稱? – user2926577 2014-09-03 23:19:35

+0

@ user2926577,是的,您可以使用插槽參數獲取行數。我已經更新了我的答案。 – Gluttton 2014-09-03 23:28:19

+0

這是有效的。謝謝!! – user2926577 2014-09-03 23:36:08