这是Efficient way to make a array of labels的后续问题。
我有一组由代码(不是设计器)制作的按钮,它们都添加到网格布局中。我想要的是能够单击该网格布局上的任何按钮并以行和列作为参数调用一个相同的函数。为什么我想要这个是因为我不想编写所有做同样事情的 15x15 函数。
有没有办法或者我应该尝试找到另一种解决方案?
附言。我所有的其他输入都是通过“转到插槽”在 qt 设计器中进行的,所以如果它必须以其他方式发生,我将一无所知。
编辑:标签数组现在是按钮数组。
这是Efficient way to make a array of labels的后续问题。
我有一组由代码(不是设计器)制作的按钮,它们都添加到网格布局中。我想要的是能够单击该网格布局上的任何按钮并以行和列作为参数调用一个相同的函数。为什么我想要这个是因为我不想编写所有做同样事情的 15x15 函数。
有没有办法或者我应该尝试找到另一种解决方案?
附言。我所有的其他输入都是通过“转到插槽”在 qt 设计器中进行的,所以如果它必须以其他方式发生,我将一无所知。
编辑:标签数组现在是按钮数组。
您可以将所有按钮连接到不带参数的插槽,然后在以下步骤中获取发送者的位置:
QObject到 QWidgetqobject_castQWidget使用的索引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()));
// ...
默认情况下,QLabel 没有“点击”信号。但是您可以使用 2 个整数(行、列)执行您自己的 QLabel,当您有一个 mouseReleaseEvent(或 mousePressEvent)时,您会发送一个如下所示的自定义信号:clicked(int row, int col)。
您还可以使用 QSignalMapper:http: //qt-project.org/doc/qt-4.8/qsignalmapper.html#details