Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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, like

    QRadioButton* 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.


  • Lifetime Qt Champion

    Hi,

    You could use lambdas for that.



  • @kitfox
    One way is to use a lambda to pass a parameter, like

    QRadioButton* 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.



  • @Bonnie
    There is, but IIRC (I think I read it somewhere) sender() == nullptr if slot called via lambda?


Log in to reply