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

3

6

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 ?

Bemuse answered 11/10, 2014 at 22:35 Comment(0)
J
9

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();
}
Jann answered 12/10, 2014 at 4:29 Comment(4)
Thanks, I have a simple inquiry related to the same question: is it possible to set value to each radio button like setData().Bemuse
@LionKing yes, documentation said that you can setIcon and setText to the button.Jann
No problem, about my inquiry, I mean I want to set hidden value or data to each radio button like setData() function to get it later. is it possible to do that.Bemuse
@LionKing Oh,I understood. No, buttons have not display or another roles, but every button is a QObject subclass so you can set custom property, using setProperty method and read it by property method.Jann
D
1

You can use the 'isChecked()' command that all qt buttons support, and check each radio button. Or, you can connect a function to the 'toggled(bool isChecked)' signal, and use that to update a value indicating which of the four radio buttons is checked.

Decelerate answered 12/10, 2014 at 0:41 Comment(2)
What about the name of each radio button, no problem if each radio button has its own name differs from the other.Bemuse
You should definitely name your radio buttons after what their labels say, and keep track of them in the code. You can use the text() command, but you have to select which radio button you use it from anyway.Decelerate
C
0

The numeric values of the four IDs should be continuous. Given that, call GetCheckedRadioButton to determine which one is selected.

Cognac answered 11/10, 2014 at 22:53 Comment(1)
is GetCheckedRadioButton function in Qt5 ?Bemuse

© 2022 - 2024 — McMap. All rights reserved.