- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 509字
- 2021-08-27 18:30:58
Accelerators and label buddies
Now, we will focus on giving the dialog some more polish. The first thing we will do is add accelerators to our widgets. These are keyboard shortcuts that, when activated, cause particular widgets to gain keyboard focus or perform a predetermined action (for example, toggle a checkbox or push a button). Accelerators are usually marked by underlining them, as follows:
We will set accelerators to our line edits so that when the user activates an accelerator for the first field, it will gain focus. Through this, we can enter the name of the first player, and, similarly, when the accelerator for the second line edit is triggered, we can start typing in the name for the second player.
Start by selecting the first label on the left-hand side of the first line edit. Press F2 and change the text to Player &A Name:. The & character marks the character directly after it as an accelerator for the widget. Accelerators may not work with digits on some platforms, so we decided to use a letter instead. Similarly, rename the second label to Player &B Name:.
For widgets that are composed of both text and the actual functionality (for example, a button), this is enough to make accelerators work. However, since QLineEdit does not have any text associated with it, we have to use a separate widget for that. This is why we have set the accelerator on the label. Now we need to associate the label with the line edit so that the activation of the label's accelerator will forward it to the widget of our choice. This is done by setting a so-called buddy for the label. You can do this in code using the setBuddy method of the QLabel class or using Creator's form designer. Since we're already in the Design mode, we'll use the latter approach. For that, we need to activate a dedicated mode in the form designer.
Look at the upper part of Creator's window; directly above the form, you will find a toolbar containing a couple of icons. Click on the one labeled Edit buddies . Now, move the mouse cursor over the label, press the mouse button, and drag from the label toward the line edit. When you drag the label over the line edit, you'll see a graphical visualization of a connection being set between the label and the line edit. If you release the button now, the association will be made permanent. You should note that when such an association is made, the ampersand character (&) vanishes from the label, and the character behind it gets an underscore. Repeat this for the other label and corresponding line edit. Click on the Edit widgets button above the form to return the form editor to the default mode. Now, you can preview the form again and check whether accelerators work as expected; pressing Alt + A and Alt + B should set the text cursor to the first and second text field, respectively.