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);


 /* 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.

Part I: Introduction to C++ and Qt 4

C++ Introduction


Introduction to Qt



Inheritance and Polymorphism

Part II: Higher-Level Programming


Introduction to Design Patterns


Generics and Containers

Qt GUI Widgets


Validation and Regular Expressions

Parsing XML

Meta Objects, Properties, and Reflective Programming

More Design Patterns

Models and Views

Qt SQL Classes

Part III: C++ Language Reference

Types and Expressions

Scope and Storage Class

Statements and Control Structures

Memory Access

Chapter Summary

Inheritance in Detail

Miscellaneous Topics

Part IV: Programming Assignments

MP3 Jukebox Assignments

Part V: Appendices

MP3 Jukebox Assignments


MP3 Jukebox Assignments

An Introduction to Design Patterns in C++ with Qt 4
An Introduction to Design Patterns in C++ with Qt 4
ISBN: 0131879057
EAN: 2147483647
Year: 2004
Pages: 268 © 2008-2020.
If you may any questions please contact us: