官术网_书友最值得收藏!

Responding to hotkeys

At this point, almost all of the features are implemented as we intended. Now, let's add some hotkeys for frequently used actions to make our application much easier to use.

You may have noticed that, when we create the actions, we occasionally add a strange & to their text, such as &File and E&xit. Actually, this is a way of setting shortcuts in Qt. In certain Qt widgets, using & in front of a character will automatically create a mnemonic (a shortcut) for that character. Hence, in our application, if you press Alt + F, the File menu will be triggered, and while the File menu is expanded, we can see the Exit action on it. At this time, you press Alt + X, and the Exit action will be triggered to let the application exit.

Now, let's give the most frequently used actions some single key shortcuts to make using them more convenient and faster as follows:

  • Plus (+) or equal (=) for zooming in
  • Minus (-) or underscore (_) for zooming out
  • Up or left for the previous image
  • Down or right for the next image

To achieve this, we add a new private method named setupShortcuts in the MainWindow class and implement it as follows:

     void MainWindow::setupShortcuts()
{
QList<QKeySequence> shortcuts;
shortcuts << Qt::Key_Plus << Qt::Key_Equal;
zoomInAction->setShortcuts(shortcuts);

shortcuts.clear();
shortcuts << Qt::Key_Minus << Qt::Key_Underscore;
zoomOutAction->setShortcuts(shortcuts);

shortcuts.clear();
shortcuts << Qt::Key_Up << Qt::Key_Left;
prevAction->setShortcuts(shortcuts);

shortcuts.clear();
shortcuts << Qt::Key_Down << Qt::Key_Right;
nextAction->setShortcuts(shortcuts);
}

To support multiple shortcuts for one action, for example, + and = for zooming in, for each action we make an empty QList of QKeySequence, and then add each shortcut key sequence to the list. In Qt, QKeySequence encapsulates a key sequence as used by shortcuts. Because QKeySequence has a non-explicit constructor with int arguments, we can add Qt::Key values directly to the list and they will be converted to instances of QKeySequence implicitly. After the list is filled, we call the setShortcuts method on each action with the filled list, and this way setting shortcuts will be easier.

Add the setupShortcuts() method call at the end of the body of the createActions method, then compile and run; now you can test the shortcuts in your application and they should work well.

主站蜘蛛池模板: 许昌县| 项城市| 恩平市| 曲阜市| 弥渡县| 黑龙江省| 嘉鱼县| 贵定县| 乌鲁木齐市| 抚宁县| 德州市| 会理县| 如东县| 凤凰县| 西乌| 白山市| 沅江市| 当涂县| 凌云县| 嘉善县| 和硕县| 巴林右旗| 二手房| 青岛市| 呼和浩特市| 资源县| 游戏| 彭山县| 庄河市| 通山县| 永州市| 申扎县| 东海县| 岳阳市| 北京市| 蕲春县| 菏泽市| 米脂县| 南康市| 宜丰县| 马龙县|