When keeping a key pressed down, then I receive a number of keyReleaseEvents() in addition to keyPressEvents(). Why is this happening and what can be done to only get a mousePressEvent() ?

When a given key is continuously pressed it results in a continuous stream of events for the associated key. You will get both keyPressEvents() [doc.qt.nokia.com] and keyReleaseEvents() [doc.qt.nokia.com] for the relevant key even if you have not released the key. You can not stop the events from being sent since they come directly from the windowing system. What you can do however is to check the autoRepeat() [qt.nokia.com] function in your key event handler and just ignore the key event if it was generated by an auto-repeating key.

See the following example for an illustration:

  1. #include <QtGui>  
  2.  
  3. class Widget : public QWidget
  4. {
  5. public:  
  6.     Widget()
  7.     {
  8.         setFocusPolicy(Qt::StrongFocus);  
  9.     }  
  10.  
  11.     void keyPressEvent(QKeyEvent *event)  
  12.     {
  13.         if(event->isAutoRepeat() ) {    
  14.             qDebug() << "keyPressEvent ignore";
  15.             event->ignore();  
  16.         } else {    
  17.             qDebug() << "keyPressEvent accept";
  18.             event->accept();
  19.         }  
  20.     }  
  21.  
  22.     void keyReleaseEvent(QKeyEvent *event)  
  23.     {
  24.         if(event->isAutoRepeat() ) {    
  25.             qDebug() << "keyReleaseEvent ignore";
  26.             event->ignore();  
  27.         } else {    
  28.             qDebug() << "keyReleaseEvent accept";
  29.             event->accept();
  30.         }
  31.     }
  32. };  
  33.  
  34. int main(int argc, char **argv)
  35. {  
  36.     QApplication app(argc, argv);  
  37.     Widget box;  
  38.     box.show();  
  39.     return app.exec();    
  40. }  

No comments

Write a comment

Sorry, you must be logged in to post a comment.