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?
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.