Search code examples
pythonqtpyqtshortcut

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


While defining the custom signal emission from within QTableView's keyPressEvent() method:

def keyPressEvent(self, e):
    if e.text()=='w':
        self.emit(SIGNAL('writeRequested'))
    if e.text()=='o':
        self.emit(SIGNAL('openRequested')) 

I am using incoming e argument to figure out what keyboard key was pressed. With this "technique" I am limited to only one character at the time. Secondly, I am not able to use a combination of Ctrl+Key, Alt+Key or Shift+Key. Third, I can't figure out what Delete and Backspaces keys are so I could compare them against e.text().

So there are few questions really...

  1. Where in Qt docs all the keyboardKeys are listed so they could be used to do a e.text()=='keyboardKey' comparison.

  2. How to handle the double-keyboard keys combinations (such as Ctrl+Key) with the "technique" I am using (sending a custom signal from inside of view's keyPressEvent()?

  3. Is there an alternative easier way to hook the keyboard keys to trigger a method or a function (so the user could use keyboard shortcuts while mouse positioned above QTableView to launch the "action")?


Solution

  • 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.