Created
March 27, 2018 15:39
-
-
Save gboeer/6760a8bb2ae76797116fcd0b78079497 to your computer and use it in GitHub Desktop.
For QT5 this is an easy way to use a QActionGroup or a QButtonGroup to allow for an exclusive selection/checking of Actions/Buttons or no selection at all.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Keywords: C++, QT, QT5, GUI, QActionGroup, QButtonGroup | |
By default a QActionGroup allows for an exclusive selection of actions (only one action can be selected at a time). | |
However there is no way to configure it out of the box to allow for exclusive selection or no selection at all. | |
Here is an easy way how to use the QActionGroup to enable also no selection, without the need to subclass it. | |
*/ | |
#include <QActionGroup> | |
#include <QAction> | |
QActionGroup * actionGroup = new QActionGroup(this); | |
// we implement a custom version of exclusive selection, which allows for no selection, so we have to disable the default here | |
actionGroup->setExclusive(false); | |
// define actions and add to the group (remember to make actions checkable) | |
QAction* action1 = new QAction("Action 1"); | |
action1->setCheckable(true); | |
QAction* action2 = new QAction("Action 2"); | |
action2->setCheckable(true); | |
QAction* action3 = new QAction("Action 3"); | |
action3->setCheckable(true); | |
actionGroup->addAction(action1); | |
actionGroup->addAction(action2); | |
actionGroup->addAction(action3); | |
connect(actionGroup, &QActionGroup::triggered, this, [=](QAction* action) { | |
// if an action is selected | |
if (action->isChecked()) | |
{ | |
// deselect all other actions except the selected one | |
QAction * action_i; | |
foreach(action_i, actionGroup->actions()) | |
if (action != action_i) action_i->setChecked(false); | |
} | |
else | |
{ | |
// at this point no action is selected and we can perform any operation that may be needed for this case | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment