Time for action – Creating a menu and a toolbar

Let's replace our boring Start new game button with a menu entry and a toolbar icon. First, select the button and press the Delete key to delete it. Then, locate Action Editor in the bottom-center part of the form editor and click on the New button on its toolbar. Enter the following values in the dialog (you can fill the Shortcut field by pressing the key combination you want to use):

Locate the toolbar in the central area (between the Type Here text and the first label) and drag the line containing the New Game action from the action editor to the toolbar, which results in a button appearing in the toolbar.

To create a menu for the window, double-click on the Type Here text on the top of the form and replace the text with &File (although our application doesn't work with files, we will follow this tradition). Then, drag the New Game action from the action editor over the newly created menu, but do not drop it there yet. The menu should open now, and you can drag the action so that a red bar appears in the submenu in the position where you want the menu entry to appear; now you can release the mouse button to create the entry.

Now we should restore the functionality that was broken when we deleted the button. Navigate to the constructor of the MainWindow class and adjust the connect() call:

connect(ui->startNewGame, &QAction::triggered,
this, &MainWindow::startNewGame);

Actions, like widgets, are accessible through the ui object. The ui->startNewGame object is now a QAction instead of a QPushButton, and we use its triggered() signal to detect whether the action was selected in some way.

Now, if you run the application, you can select the menu entry, press a button on the toolbar, or press the Ctrl + N keys. Either of these operations will cause the action to emit the triggered() signal, and the game configuration dialog should appear.

Like widgets, QAction objects have some useful methods that are accessible in our form class. For example, executing ui->startNewGame->setEnabled(false) will disable all ways to trigger the New Game action.

Let's add another action for quitting the application (although the user can already do it just by closing the main window). Use the action editor to add a new action with text Quit, object name quit, and shortcut Ctrl + Q. Add it to the menu and the toolbar, like the first action.

We can add a new slot that stops the application, but such a slot already exists in QApplication, so let's just reuse it. Locate the constructor of our form in mainwindow.cpp and append the following code:

connect(ui->quit, &QAction::triggered,
        qApp,     &QApplication::quit);