QActionGroup类用来将菜单中的子菜单(QAction)分组。在某些情况下,对子菜单(QAction)分组非常有用。
一个应用场景是:在文本编辑时,涉及到多种对齐方式,如:左对齐、右对齐、两端对齐、居中对齐;同时还有字体加粗、斜体功能。我们可以把功能相似的子菜单分为一组,如将对齐方式为分一组,组中子菜单每次只能有一个激活选中,如:对齐方式,你只能选择其中的一种,不可能同时选择多种对齐方式。实现代码如下:
#include "QtWidgetsApplication1.h"
#include<QWidgetAction>
#include<QCheckBox>
QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
auto leftAlignAct = new QAction(QString::fromLocal8Bit("左对齐"), this);
leftAlignAct->setCheckable(true);
leftAlignAct->setChecked(true);
auto rightAlignAct = new QAction(QString::fromLocal8Bit("右对齐"), this);
rightAlignAct->setCheckable(true);
auto justifyAct = new QAction(QString::fromLocal8Bit("两端对齐"), this);
justifyAct->setCheckable(true);
auto centerAct = new QAction(QString::fromLocal8Bit("居中对齐"), this);
centerAct->setCheckable(true);
auto alignmentGroup = new QActionGroup(this);
alignmentGroup->setExclusive(true);
alignmentGroup->addAction(leftAlignAct);
alignmentGroup->addAction(rightAlignAct);
alignmentGroup->addAction(justifyAct);
alignmentGroup->addAction(centerAct);
auto pMenu = new QMenu(QString::fromLocal8Bit("对齐"), this);
pMenu->addAction(leftAlignAct);
pMenu->addAction(rightAlignAct);
pMenu->addAction(justifyAct);
pMenu->addAction(centerAct);
pMenu->setDefaultAction(leftAlignAct);
auto pSepAction = pMenu->addSeparator();
pMenu->addAction(pSepAction);
auto pBoldCheckbox = new QCheckBox(this);
pBoldCheckbox->setText(QString::fromLocal8Bit("粗体"));
QWidgetAction* pBoldAction = new QWidgetAction(this);
pBoldAction->setDefaultWidget(pBoldCheckbox);
pMenu->addAction(pBoldAction);
auto pItaliCheckbox = new QCheckBox(this);
pItaliCheckbox->setText(QString::fromLocal8Bit("倾斜"));
QWidgetAction* pItalicAction = new QWidgetAction(this);
pItalicAction->setDefaultWidget(pItaliCheckbox);
pMenu->addAction(pItalicAction);
this->menuBar()->addMenu(pMenu);
}
运行结果如下:
需要注意的问题:
- 要使子菜单互斥,必须将每个子菜单的checkable属性设置为true,否则当选中该子菜单时,其前面的单选小圆点不会出现。
- 设置组中默认选中菜单时,setChecked必须设置为true,且setChecked必须在setCheckable(true)后面,否则该子菜单不会默认选中。这很好理解,只有菜单是checkable的,设置菜单选中才有意义。
- 因为子菜单前面有类似单选按钮似的小圆点,调用如下:
QAction *addAction(const QIcon &icon, const QString &text)
带有图标的函数创建的子菜单时,子菜单前面不会出现图标。
- 要使组中的各个子菜单互斥,即每次只能选择其中的一个,则必须调用如下代码设置组互斥:
alignmentGroup->setExclusive(true);
默认情况下QActionGroup是互斥的,所以上句代码也可以不调用。
- 请留意带有复选框子菜单的创建方法。