|GUI Programming with Python: QT Edition|
|Prev||Chapter 13. Actions: menus, toolbars and accelerators||Next|
The old vi or Emacs lags amongst us know this already, just as the WordPerfect veterans know: regardless of what Rob Pike, designer of the Plan9 operating system, says, using a keyboard can actually be preferable to grabbing the mouse for every trifle. Giving the vast majority of interface actions in your application a keyboard accelerator is therefore a Good Thing, and is highly encouraged.
Note the subtle difference between a keyboard accelerator and a keyboard shortcut. Shortcuts are generally combinations of the Alt key and a letter. They are indicated in menus and dialogs by an underscore, and created by simply prefixing an ampersand (&) to the shortcut letter. Shortcuts only function in the context of a menu or dialog box: that's why Alt-F generally opens the file menu, but Alt-Q doesn't close the application unless the file menu happens to be open. Accelerators are important and every menu option and every widget on a dialog ought to be associated with one.
Accelerators, on the other hand, are generally combinations of CTRL and some other key (or, for the WordPerfect-conditioned octopodi amongst us, all modifiers together; CTRL-SHIFT-ALT-F12, anyone?). If the focus of your application is on the document (or on a text field in a dialog box), then your user will want to use shortcuts for everything.
There are a number of standard accelerators, such as CTRL-X for the cut action, but every application is free to add to that store. You associate accelerators with QActions, with the setAccel function. For actions that are not associated with QActions, you can create QAccel objects on their own, and connect them to a slot of your choice.
QAccel offers one especially handy class method, stringToKey, which takes a string describing an accelerator and returns and integer value that represents a key combination to PyQt. The format is very clear: "Ctrl+O", for instance. Even better, because this is a string, you can translate this string using pygettext or PyQt's tr() to localize the keyboard shortcuts for different countries. This is not possible if you use the Qt constants that represent keys, such as Qt.CTRL + Qt.Key_O.