[PyQt] Catching key events

Mark Summerfield mark at qtrac.eu
Mon Jan 19 10:02:17 GMT 2009


On 2009-01-17, Frédéric wrote:
> On vendredi 16 janvier 2009, Frédéric wrote:
> > 1) catching key events
> >
> > I found that I have to implement the keyPressEvent() method. I did this
> > in the mainWindow, but the behaviour depend where is the focus. And as I
> > want to catch arrow keys, it also change the focus! What is the proper
> > way to do this? I also want to rebind key TAB, to avoid changing the
> > focus, space, and enter...
>
> Ok, I solved most of my problems using grabKeyboard()/releaseKeyboard()
> methods.
>
> I still have an issue: when I hold down a key, once the repeat starts, I
> receive both KeyPressed and KeyReleased events. This is a different
> behaviour as PyGTK, where I only received the key-pressed-event while
> holding it down, and the key-release-event when I release the key.
>
> Is there a way to do this in PyQt? I want to start the motor head when I
> press the key, and stop it when I release the key. Now, it does not work,
> as the motor is started/stopped too quickly (which is not very good)...

Frédéric,

I suspect that using grabKeyboard()/releaseKeyboard() is not the right
approach---for example, I've never seen them used in practice and have
never used them myself.

PyQt has an event handling hierarchy, and IMO it is best to start with
the least powerful approach and work up 'til you get what you need.

So if you want to catch particular keys you could create a QShortcut for
each key sequence in the main window's __init__ and connect each
shortcut to a method.

If that isn't sufficient, then you could try reimplementing
keyPressEvent()---and to propagate key event you don't want to handle
yourself just call the base class version with the arguments you
received. (And of course see David's reply.)

If you want more control than that you could reimplement event(), or you
could add one or more eventFilters() (but never use many of them since
they can hurt performance). And that's not quite all. Keep in mind that
PyQt is _different_ from Gtk so IMO it is best to find the PyQt-ish
approach rather than to attempt a straight conversion from Gtk to PyQt
code.


-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Programming in Python 3" - ISBN 0137129297




More information about the PyQt mailing list