10.1.  QActions, QMenus, and QMenuBars

[ 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 QWidgets can have QActions. Some widgets provide the list of QActions 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 QActions. 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:

The QMainWindow in Figure 10.2 has a single menu bar that contains a single menu that offers two choices.

Figure 10.2.  QMenu

QMenu


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 QActions 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 menu button. It is called a context menu because the menu always depends on the context (which QWidget or item is currently selected or focused).