[PyQt] Catching key events Re: [PyQt] Catching key events
Mark Summerfield
mark at qtrac.eu
Mon Jan 19 16:50:00 GMT 2009
On 2009-01-19, Frédéric wrote:
> Le 19/1/2009, "Mark Summerfield" <mark at qtrac.eu> a écrit:
> >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.
>
> I totally agree that mimic PyGTK is not very efficient. In fact, I'm
> porting my app to Qt this way to quickly have something running, and
> test all other problems (packaging, and so). Then, I plan to redesign
> it, and use all Qt great features.
>
> Even if using grabKeyboard()/releaseKeyboard() in a few points works
> really great, exactly how I want, I will try QShortcut...
>
> About keyPressEvent, I'm using it, and it works (thanks to David),
> except that the repeat sends press followed by release events, and I
> really need to only get the press event when the key is pressed, and the
> release one when it is released. I didn't find yet a way to do that. At
> which level this feature is implemented, so I can try to change it?
> Should I go down to the event() callback?
I'd stick to reimplementing keyPressEvent. The QKeyEvent parameter can
tell you if the press is due to autorepeat or a genuine new keyclick.
--
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