Simple way to have radio buttons call same function with different parameter?
-
I'm creating a set of
QRadioButton
where each button is triggering essentially the same action but with a different value. For example:QRadioButton* bn1 = new QRadioButton("1"); connect(bn1, &QRadioButton::clicked, this, &MyClass::setStation1); QRadioButton* bn2 = new QRadioButton("2"); connect(bn2, &QRadioButton::clicked, this, &MyClass::setStation2); QRadioButton* bn2 = new QRadioButton("3"); connect(bn3, &QRadioButton::clicked, this, &MyClass::setStation3);
It would be convenient to replace each of the setStation*() slot methods with a single method
setStation(int station)
and just pass the index of the station. Is there a way to do this? -
@kitfox
One way is to use a lambda to pass a parameter, likeQRadioButton* bn1 = new QRadioButton("1"); connect(bn1, &QRadioButton::clicked, this, [=] () { this->setStation(1); } ); QRadioButton* bn2 = new QRadioButton("2"); connect(bn2, &QRadioButton::clicked, this, [=] () { this->setStation(2); } );
This example could also be done with QSignalMapper Class, but lambdas are more usual now.
-
Hi,
You could use lambdas for that.
-
@kitfox
One way is to use a lambda to pass a parameter, likeQRadioButton* bn1 = new QRadioButton("1"); connect(bn1, &QRadioButton::clicked, this, [=] () { this->setStation(1); } ); QRadioButton* bn2 = new QRadioButton("2"); connect(bn2, &QRadioButton::clicked, this, [=] () { this->setStation(2); } );
This example could also be done with QSignalMapper Class, but lambdas are more usual now.
-
There is also another old-fashioned way : getting data from the sender.
void MyClass::setStation() { if(QRadioButton *button = qobject_cast<QRadioButton*>(sender())) { QString text = button->text(); if(text == "1") { } else if(text == "2") { } } }
But lambdas are way more flexible.