The straightforward way is to use QObject::sender()
in the button press slot to find out which button emitted the signal. You should then iterate over the vector of buttons:
QObject* obj = sender();
for(int i=0;i<buttonVector.count();i++)
{
if( obj == qobject_cast<QObject *>(buttonVector[i]))
{
...
}
}
One workaround is to use QObject::setObjectName
and set some names to the buttons you add :
button.setObjectName(QString("%1").arg(i));
And in the slot you can retrieve the button number using the object name :
void MainWindow::buttonClicked()
{
QPushButton *button = qobject_cast<QPushButton *>(QObject::sender());
int number = button->objectName().toInt();
}
Another way is to use the QSignalMapper
class which collects a set of parameterless signals, and re-emits them with integer, string or widget parameters corresponding to the object that sent the signal. So you can have one like:
QSignalMapper * mapper = new QSignalMapper(this);
QObject::connect(mapper,SIGNAL(mapped(int)),this,SLOT(buttonClicked(int)));
When newing your buttons, you can connect the clicked()
signal of the button to the map()
slot of QSignalMapper
and add a mapping using setMapping
so that when clicked()
is signaled from a button, the signal mapped(int)
is emitted:
button = new QPushButton();
QObject::connect(button, SIGNAL(clicked()),mapper,SLOT(map()));
mapper->setMapping(button, i);
This way whenever you click a button, the mapped(int)
signal of the mapper is emitted containing the button number and consequently buttonClicked
is called with a parameter containing the button number.