[ fromfile: menus.xml id: menus ]
QAction, derived from QObject, is a base class for user-selected actions. It provides a rich interface that can be used for a wide variety of actions, as you soon see. The QWidget interface enables each widget to maintain a QList<QAction*>.
All QWidget
s can have QAction
s.
Some widgets provide the list of QAction
s via a context menu, others via menu bar.
See setContextMenuPolicy()
API docs for details on how to provide context menus from widgets.
A QMenu is a QWidget that provides a particular kind of view for a collection of QAction
s.
A QMenuBar is a collection of menus, usually found in a QMainWindow.
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[77]. A QMenu can have another QMenu as its parent, in which case it becomes a submenu.
To help the user make the right choice, each QAction 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 QMainWindow
in Figure 10.2 has a single menu bar that contains a single menu that offers two choices.
Example 10.2 shows the code that sets up that menu bar.
The function QMainWindow::menuBar()
returns a pointer to the QMenuBar which is a child of the QMainWindow.
The menuBar()
function creates and returns a pointer to an empty QMenuBar child if the menu bar does not already exist.
Example 10.2. src/widgets/dialogs/messagebox/dialogs.cpp
[ . . . . ] /* Insert a menu into the menubar. */ QMenu* menu = new QMenu(tr("&Questions"), this); QMainWindow::menuBar()->addMenu(menu); /* Add some choices to the menu. */ menu->addAction(tr("&Ask question"), this, SLOT(askQuestion()), tr("Alt+A")); menu->addAction(tr("Ask a &dumb question"), this, SLOT(askDumbQuestion()), tr("Alt+D")); }
<include src="src/widgets/dialogs/messagebox/dialogs.cpp" mode="cpp" href="src/widgets/dialogs/messagebox/dialogs.cpp" id="dialog-menubar" segid="menu"/>
Each call to QMenu::addAction(text, target, slot, shortcut)
creates an unnamed QAction and adds it to the QMenu.
It then calls its hidden base class function, QWidget::addAction(QAction*)
, which adds the newly created QAction to the list of QAction
s of the QMenu for use in a context menu.
The latter call adds the new action to the menu's QList<QAction*>.
[77] A context menu is usually activated by clicking the right mouse button or by pressing the button. It is called a context menu because the menu always depends on the context (which QWidget or item is currently selected or focused).
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |