Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to QButtonGroup that allows no selection?

I'm writing a qt-based c++ application. I have a number of buttons that I want to be mutually exclusive - only one can be toggled at a time. I generally use a QButtonGroup for this - it provides a nice logical way to manage sets of buttons. When one gets pressed, the previously-pressed one gets unpressed, which is exactly the behavior I want.

This time, however, I'd like to allow for the group to be entirely unchecked. Unfortunately this seems to be disallowed by QButtonGroup:

exclusive : bool

This property holds whether the button group is exclusive.

If this property is true then only one button in the group can be checked at any given time. The user can click on any button to check it, and that button will replace the existing one as the checked button in the group.

In an exclusive group, the user cannot uncheck the currently checked button by clicking on it; instead, another button in the group must be clicked to set the new checked button for that group.

There are a number of ways to work around this, of course. I'm wondering if there's a pre-made alternative to QButtonGroup that allows this behavior, so that 1) I'm not reinventing the wheel and 2) I can stay within idiomatic qt to make project management easier in the future.

Any suggestions?

like image 678
tmpearce Avatar asked Mar 02 '13 18:03

tmpearce


1 Answers

In Qt5, I use a similar solution as Laurent Michel's, but using the release event instead of the press event:

// Allow to uncheck button in exclusive group
void CustomButton::mouseReleaseEvent(QMouseEvent* a_Event) {
    if(group()->checkedId()==group()->id(this)) {
        if(isDown()) group()->setExclusive(false);
    }
    QToolButton::mouseReleaseEvent(a_Event);
    group()->setExclusive(true);
}
like image 169
Gabotronics Avatar answered Sep 27 '22 15:09

Gabotronics