5

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;
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Oliver
  • 1,576
  • 1
  • 17
  • 31

2 Answers2

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

}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 1
    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. – Oliver Mar 30 '17 at 03:31
  • Would there be a more efficient way that bypasses individual radio buttons? – Oliver Mar 30 '17 at 03:34
  • I used Qt designer, and just made all of the radio buttons the groupbox's children by dragging them in. – Oliver Mar 30 '17 at 03:34
  • 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. – Oliver Mar 30 '17 at 03:41
0

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();
Hani Shams
  • 331
  • 3
  • 5