0

I have QLineEdits and QCheckBoxes QVectors - I also have a QPushButton QVector which when an element is pressed, the corresponding QLineEdit and QCheckBox are also removed.

How can I find out which button was pressed to determine which index to remove? Currently I am just using Checkboxes right now which is easy but a little bulky for my liking.

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

2

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.

Nejat
  • 31,784
  • 12
  • 106
  • 138
  • 1
    There's also QButtonGroup, although for this use case is comparable to QSignalMapper – Frank Osterfeld Jun 03 '15 at 05:32
  • The QSignalMapper is a lovely solution which I managed to implement. Only thing I have found to be a little bit annoying is the fact that if I delete a button, I have to manage the mappings manually since mapping->removeMapping() doesn't resize anything. Thanks @Negat ! – lachycharts Jun 03 '15 at 06:59