Qt在线文档地址:
https://doc.qt.io/qt-5/qactiongroup.html
此为官方文档的摘抄,笔者无版权。
使用QActionGroup就会使得加入QActionGroup的QAction只有一个被按下,同样的用法的还有QButtonGroup
需要注意的是你必须增加setCheckable(true);不然按钮按下就弹起来因此文档中还需增加以下代码:
leftAlignAct->setCheckable(true);
rightAlignAct->setCheckable(true);
justifyAct->setCheckable(true);
centerAct->setCheckable(true);
QActionGroup一个行动组默认是排他性的; 它确保在任何时候只有一个可检查操作处于活动状态。 如果您想将可检查的操作分组而不排除它们,您可以通过调用setExclusive(false)来打开排他性,这你就可以多个工具同时按下。
Detailed Description
In some situations it is useful to group QAction objects together. For example, if you have a Left Align action, a Right Align action, a Justifyaction, and a Center action, only one of these actions should be active at any one time. One simple way of achieving this is to group the actions together in an action group.
Here's a example (from the Menus example):
alignmentGroup = new QActionGroup(this);
alignmentGroup->addAction(leftAlignAct);
alignmentGroup->addAction(rightAlignAct);
alignmentGroup->addAction(justifyAct);
alignmentGroup->addAction(centerAct);
leftAlignAct->setChecked(true);
Here we create a new action group. Since the action group is exclusive by default, only one of the actions in the group is checked at any one time.
A QActionGroup emits an triggered() signal when one of its actions is chosen. Each action in an action group emits its triggered() signal as usual.
As stated above, an action group is exclusive by default; it ensures that at most only one checkable action is active at any one time. If you want to group checkable actions without making them exclusive, you can turn off exclusiveness by calling setExclusive(false).
By default the active action of an exclusive group cannot be unchecked. In some cases it may be useful to allow unchecking all the actions, you can allow this by calling setExclusionPolicy(QActionGroup::ExclusionPolicy::ExclusiveOptional).
Actions can be added to an action group using addAction(), but it is usually more convenient to specify a group when creating actions; this ensures that actions are automatically created with a parent. Actions can be visually separated from each other by adding a separator action to the group; create an action and use QAction's setSeparator() function to make it considered a separator. Action groups are added to widgets with the QWidget::addActions() function.
See also QAction.
这里有比别人翻译的一篇博文,可以参考下: