Search code examples
c++qtradio-buttonqt5

How to find out which radio button was chosen by the user?


I have four radio buttons, the user must choose one of the four radio buttons.

The problem is each radio button has its own name that differs from the others.

How to find out which radio button was chosen by the user ?


Solution

  • Add the buttons into a GroupBox and use findChildren, after this you can use QButtonGroup or simply iterate through all Buttons list and check name of radiobutton. It is efficient way because it works with 4 button or 1000, you should write big code if you have many buttons.

    void MainWindow::on_pushButton_15_clicked(){
        QButtonGroup group;
        QList<QRadioButton *> allButtons = ui->groupBox->findChildren<QRadioButton *>();
        qDebug() <<allButtons.size();
        for(int i = 0; i < allButtons.size(); ++i)
        {
            group.addButton(allButtons[i],i);
        }
        qDebug() << group.checkedId();
        qDebug() << group.checkedButton();
    }