c++qtcheckboxmutual-exclusion

Qt mutually exclusive checkboxes


I want to make a group of mutually exclusive checkboxes in Qt (no Qt Designer or any of that fancy stuff). With three checkboxes I can do something like this in the action function:

void mainWindow::checkbox1action() {
  // mutual exclusivity
  checkbox2->setChecked(!checkbox1->isChecked());
  checkbox3->setChecked(!checkbox1->isChecked());

  // action for checkbox 1
  ...
}

and likewise for all the other checkboxes. However, with, say, 15 checkboxes for colors, this action becomes very repetitive. Is there any other, better way to do this for many checkboxes?


Solution

  • You can add your checkboxes into a QButtonGroup and set it to be exclusive.

    QButtonGroup *group = new QButtonGroup(this);
    group->setExclusive(true);
    group->addButton(checkbox1);
    group->addButton(checkbox2);
    

    There is also QRadioButton, which is automatically exclusive within the same widget.