Check for a key with Qt

I play with graphics, and I implemented a simple camera movement using the arrow keys. My first approach was to override keyPressEvent to do something like this:

 switch(key) { case up: MoveCameraForward(step); break; case left: MoveCameraLeft(step); break; ... } 

This does not work as I would like. When I press and hold, for example, the “forward” button, the camera moves forward with “stepped” units, then stops for a while, and then continues to move. I assume that an event is generated this way to avoid multiple events in the case of a slightly long keystroke.

So, I need to poll the keyboard in my Paint() routine. I have not found how to do this with Qt. I was thinking about having a map<Key, bool> that would be updated in keyPressEvent and keyReleaseEvent and poll this map in Paint() . Any better ideas? Thanks for any ideas.

+8
c ++ event-handling qt keyboard-events
source share
4 answers

So, I need to poll the keyboard in my Paint () program. I did not find how to do this with Qt. I was thinking of a map that would be updated in keyPressEvent and keyReleaseEvent and poll this map in Paint ().

The second method is what I would do, except that I used a continuous QTimer periodic event to poll the map from the keyboard and call the QWidget :: Update () function when necessary, to display the widget instead. Performing operations without drawing inside Paint () is strongly discouraged for many reasons, but I do not know how to explain this.

+6
source share

This does not solve the general problem of detecting keys, but if you are only looking for keyboard modifiers (shift, ctrl, alt, etc.), you can get it through the static QApplication::keyboardModifiers() and QApplication::queryKeyboardModifiers() .

+4
source share

There is no Qt API to check if a key is pressed or not. You may need to write separate code for different platforms and add some #ifdef logic.

On Windows, you can use GetKeyState() and GetKeyboardState() declared in windows.h .

+3
source share

This is not straightforward when using Qt, but the Gluon team is working on this particular problem (along with a bunch of others). GluonInput solves the problem and is available as part of Gluon: http://gluon.gamingfreedom.org/ This is also a good Qt-like API, so for now you should use it.

+2
source share

All Articles