Do I need to check one by one to see which radio object is checked in a group in Qt

I know that I can use this code to find out which switch is set in Qt:

int checkButton;
if( ui->radioButton_0->isChecked() ){
    checkButton = 0;
}else if(ui->radioButton_1->isChecked()){
    checkButton = 1;
}else if 
...

      

Is there any easier way to find out which switch is set in a group in Qt. I think it is really useful if there is such an easier way when the radio button group is large. The code might look like this:

int checkbutton = groupName.getCheckButtonIngroup();

      

+3


source to share


2 answers


Also we can put multiple radio objects in a groupbox in Qt Designer and after that find the child groups of the groupbox, add children to the buttonGroup and use the checkedId or checkedButton methods.



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

      

+1


source


First of all, you need to add all radio buttons to the button group. This can be done in two ways:

  • In Qt Designer, select all the radio buttons you want to add and select Assign to button group

    from the context menu.
  • From the code. Create a new QButtonGroup and add buttons there QButtonGroup::addButton

    .


Then at any time you can find out which button is checked:

  • If you need a pointer to the marked button, use QButtonGroup::checkedButton

    .

  • If you need multiple buttons, you need to add the buttons to the group manually using addButton(QAbstractButton* button, int id)

    . After that use QButtonGroup::checkedId

    to get the ID of the checked button.

0


source







All Articles