简体   繁体   中英

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;

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

}

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 :

在此处输入图像描述

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

QAbstractButton *button = ui->buttonGroup->checkedButton();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM