How to handle keyboard shortcuts using keyPressEvent()? And should it be used for it?

荒凉一梦 提交于 2019-12-04 21:54:40

If you look at the signature of keyPressEvent() you will see that the e argument you describe in your question is of type QKeyEvent.

QKeyEvent instances have a method key() which returns an integer that can be matched against constants in the enum Qt.Key.

For example:

if e.key() == Qt.Key_Backspace:
    print 'The backspace key was pressed'

Similarly, QKeyEvent has a method modifiers(). Because there can be multiple keyboard modifiers pressed at once, you need to use this a little differently. The result from modifiers() is the binary OR of one or more of the constants in the Qt.KeyboardModifier enum. To test if a given modifier is pressed, you need to perform the binary AND. For example:

if e.modifiers() & Qt.ShiftModifier:
    print 'The Shift key is pressed'

if e.modifiers() & Qt.ControlModifier:
    print 'The control key is pressed'

if e.modifiers() & Qt.ShiftModifier and e.modifiers() & Qt.ControlModifier:
    print 'Ctrl+Shift was pressed'

Note: In the example above, if both ctrl+shift were pressed, then all three if statements execute, in sequence.

Just for completeness and if you want more difficult sequences (ctrl-c followed by ctrl-k for example) just use QKeySequence as shortcut of a QAction which can be added to any QWidget.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!