Search code examples
c++qtqt5qradiobuttonqgroupbox

QGroupBox find selected Radio Button


I have created a simple UI consisting of a QGroupBox with a bunch of QRadioButtons (32 to be exact) and I want to be able to find the selected one.

I've looked at forums and things, but the answers I've found don't work, and one referenced documentation on a nonexistant method of QGroupBox.

Given the below snippet, how would I find the selected QRadioButton, if any?

QGroupBox* thingGroup = ui->thingGroupBox;

Solution

  • If you want to get it when you select one of them you could use the toogled signal, connect it to some slot and use the sender () function and convert it to QRadioButton.

    *.h

    public slots:
        void onToggled(bool checked);
    

    *.cpp

    QGroupBox *thingGroup = ui->groupBox;
    
    QVBoxLayout *lay = new QVBoxLayout;
    
    thingGroup->setLayout(lay);
    
    for(int i = 0; i < 32; i++){
        QRadioButton *radioButton = new QRadioButton(QString::number(i));
        lay->addWidget(radioButton);
        connect(radioButton, &QRadioButton::toggled, this, &{your Class}::onToggled);
    }
    

    slot:

    void {your Class}::onToggled(bool checked)
    {
        if(checked){
            //btn is Checked
            QRadioButton *btn = static_cast<QRadioButton *>(sender());
        }
    
    }