2

I have a QT application with qcheckboxes. I would like to achive that one checkbox is always checked and i can check as much as i want, but one is always must be checked. How can i do this?

Kaguro
  • 67
  • 9
  • Connect the signals. If you detect that there's no others that are checked, you can automatically select whichever should be checked. – ChrisMM Feb 04 '20 at 14:46
  • 1
    You can use a QButtonGroup and make it non exclusive and connect to the https://doc.qt.io/qt-5/qbuttongroup.html#buttonToggled-1 signal – drescherjm Feb 04 '20 at 14:57
  • ty @drescherjm it works too! :) – Kaguro Feb 04 '20 at 15:07

1 Answers1

3

There is probably a more elegant way to do this, but I'd suggest just using signals.

Somewhere, probably constructor, you would connect the signal

connect( chkOne, &QCheckBox::toggled, this, &Test::onCheckboxOne );

Then, in the function you've connected it to, simply check whether anything else is checked. For this, I used a variable called total_checked.

void Test::onCheckboxOne( bool checked ) {
    disconnect( chkOne, &QCheckBox::toggled, this, &Test::onCheckboxOne );
    if ( !checked ) {
        if ( total_checked == 1 )
            this->chkOne->setCheckState( Qt::Checked );
        else
            --total_checked;
    } else {
        ++total_checked;
    }
    connect( chkOne, &QCheckBox::toggled, this, &Test::onCheckboxOne );
}

This would become impractical if you have a lot of checkboxes, unless (once non are selected), you want a specific checkbox set, in which case the above would be a handler for all checkbox signals.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48