Search code examples
pythonpython-3.xpyqtpyqt5qkeyevent

How to change space bar behaviour in PyQt5, Python3


I made a ui for work using PyQt5 and Python3. Additionally to clicking the buttons, I want to execute specific actions by pressing specific keys on my keyboard e.g. the space bar. I used the following to do so:

def keyPressEvent(self, event):
    key = event.key()

    if key == Qt.Key_Space:
        print('space')
    elif key == Qt.Key_W:
        print('w')

Instead of printing 'space', it presses the focused button in the ui, when I'm pressing the space bar. Just like I hit return. Although pressing the 'W'-key prints 'w' as expected.

I already searched here at stackoverflow and other where in the web as well, but I found nothing really helpfull. The best I got was this one here. But it's using PyQt4.3 and copy and paste the code to my editor just brought me some errors. I thought the approach was a good one, but I were not able to transfer this to PyQt5.


Solution

  • With S. Nick's very useful answer I were able to come to a solution that really fits my needs.

    class MyPushButton(QPushButton):
        def __init__(self, *args):
            QPushButton.__init__(self, *args)
    
        def event(self, event):
            if (event.type() == QEvent.KeyPress) and (event.key() == Qt.Key_Space):
                print(foo)
    
                return True
    
            return QPushButton.event(self, event)
    

    So, that's it. Whenever I press the space key on my keyboard now it just prints foo and nothing else. Where print(foo) is just a place-holder for whatever I wish to do, obviously.