您可以將所有的按鈕連接到不帶參數的插槽,然後獲得在這個步驟發送的位置:
- 鑄通過
qobject_cast
- 發件人
QObject
到一個QWidget使用QLayout::indexOf(QWidget *widget)
- 檢索
QWidget
的索引然後得到與QGridLayout::getItemPosition(int index, int *row, int *column, int *rowSpan, int *columnSpan)
行,列,列間距和行間距的示例代碼應該是這樣的:
void MyWidgetWithAllLabels::commonSlot()
{
QWidget *buttonWidget = qobject_cast<QWidget*>(sender());
if (!buttonWidget)
return;
int indexOfButton = ui->gridLayout->indexOf(buttonWidget);
int rowOfButton, columnOfButton, rowSpanOfButton, columnSpanOfButton;
ui->gridLayout->getItemPosition(indexOfButton,
&rowOfButton, &columnOfButton, &rowSpanOfButton, &columnSpanOfLabel);
// Now you can get a reference to that specific QPushButton
QLayoutItem *item = ui->gridLayout->itemAtPosition(rowOfButton, columnOfButton);
QPushButton *clickedButton = qobject_cast<QPushButton*>(item->widget());
if (!clickedButton)
return;
// ... do something with that clickedButton
}
參照在相關的職位代碼,您可以將按鈕連接到插槽是這樣的:
connect(ui->tile_0_0, SIGNAL(clicked()),
this, SLOT(commonSlot()));
connect(ui->tile_0_1, SIGNAL(clicked()),
this, SLOT(commonSlot()));
// ...
你有沒有想過使用帶自定義背景而不是標籤的按鈕? – ariwez
是的我沒有意識到標籤沒有點擊功能,所以我將它們改爲按鈕。 – Tremnor