QActions, QMenus, and QMenuBars
A QAction is a QObject that is a base class for user-selected actions. It provides a rich interface that can be used for a wide variety of actions, as we will soon see. The QWidget interface enables each widget to maintain a QList.
A QMenu is a QWidget that provides a particular kind of view for a collection of QActions. A QMenuBar is a collection of menus.
When the parent of a QMenu is a QMenuBar, the QMenu appears as a pull-down menu with a familiar interface. When its parent is not a QMenuBar it can pop up, like a dialog, in which case it is considered a context menu.[2] A QMenu can have another QMenu as its parent, in which case it becomes a submenu.
[2] A context menu is usually activated by clicking the right mouse button or by pressing the "menu" button. It is called a context menu because the menu always depends on the context (which QWidget is currently selected or focused).
To help the user make the right choice, each action can have the following:
- Text and/or icon that appears on a menu and/or button
- An accelerator or a shortcut key
- A "What's this?" and a tool-tip
- A way to toggle the state of the action between visible/invisible, enabled/disabled, and checked/not checked
- changed(), hovered(), toggled(), and TRiggered() signals
The Dialog in Example 11.4 had a menubar with a single menu that gave two choices.
Example 11.18 shows the code that sets up that menubar.
Example 11.18. src/widgets/dialogs/messagebox/dialogs.cpp
[ . . . . ] /* Insert a menu into the menubar */ QMenu *menu = new QMenu("&Questions", this); QMainWindow::menuBar()->addMenu(menu); /* Add some choices to the menu */ menu->addAction("&Ask question", this, SLOT(askQuestion()), tr("Alt+A")); menu->addAction("Ask a &dumb question", this, SLOT(askDumbQuestion()), tr("Alt+D")); } |
The calls to QMenu::addAction(text, target, slot, shortcut) each create an unnamed QAction and call QWidget::addAction(QAction*) to install it in the menu. The latter call adds the new action to the menu's QList.