您可以将所有按钮连接到不带参数的插槽,然后在以下步骤中获取发送者的位置:
- 通过将发件人投射
QObject
到 QWidgetqobject_cast
- 检索
QWidget
使用的索引QLayout::indexOf(QWidget *widget)
- 然后用
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()));
// ...