QGroupBox find selected Radio Button
Asked Answered
M

2

6

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;
Magda answered 30/3, 2017 at 1:6 Comment(1)
Do you want to get it when you select or at any time?Decreasing
D
5

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());
    }

}
Decreasing answered 30/3, 2017 at 3:17 Comment(4)
The only problem with this though is that I have 32 radio buttons, which would mean I'd have to copy-paste the same line 32 times. I only need to get the right radio button once the client presses a 'Next' button.Magda
Would there be a more efficient way that bypasses individual radio buttons?Magda
I used Qt designer, and just made all of the radio buttons the groupbox's children by dragging them in.Magda
Hang on, my bad, your code does exactly as I wished. I thought that the *.h segment was required for each radio button. Accepting this answer now, thanks for your help.Magda
S
2

I guess it is easier to identify which button is checked using a QButtonGroup, just remember to select buttons in "Design mode" then right-click and select assign to button group :

enter image description here

To identify the checked button, you can use QButtonGroup's checkedButton method:

QAbstractButton *button = ui->buttonGroup->checkedButton();
Sung answered 11/7, 2022 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.