English Deutsch

How to catch enter key events

Overview

There are many different situations where you can use the enter key, e.g. to start a search action. But implementing something like this is not that easy – Qt catches enter keys before you even get the event.

Solution

Fortunately, Qt allows to reimplement the general event catching method. You need a new class with a method like this:

  1. bool eventFilter(QObject *obj, QEvent *event);

That’s everything:

  1. class keyEnterReceiver : public QObject
  2. {
  3.     Q_OBJECT
  4.  
  5. protected:
  6.     bool eventFilter(QObject *obj, QEvent *event);
  7. };

Now, we have to implement the method:

  1. bool keyEnterReceiver::eventFilter(QObject *obj, QEvent *event)
  2. {
  3.     if(event->type() == QEvent::KeyPress)
  4.     {
  5.         QKeyEvent *key = static_cast<QKeyEvent *>(event);
  6.  
  7.         if((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return))
  8.         {
  9.             //Enter or return was pressed
  10.         }
  11.         else
  12.         {
  13.             return QObject::eventFilter(obj, event);
  14.         }
  15.         return true;
  16.     }
  17.     else
  18.     {
  19.         return QObject::eventFilter(obj, event);
  20.     }
  21.  
  22.     return false;
  23. }

That was quiet fast – so here is a detailled explanation:

Key pressed?

First, we check if any key was pressed. If not, it is a event that has nothing to do with keys – and Qt should handle it:

  1. bool keyEnterReceiver::eventFilter(QObject *obj, QEvent *event)
  2. {
  3.     if(event->type() == QEvent::KeyPress)
  4.     {
  5.         ...
  6.     }
  7.     else
  8.     {
  9.         return QObject::eventFilter(obj, event);
  10.     }
  11.  
  12.     return false;
  13. }

Convertion

We got a QEvent as a parameter. To read out which key was pressed, we need to convert the QEvent to a QKeyEvent:

  1. QKeyEvent *key = static_cast<QKeyEvent *>(event);

Enter/Return or another key?

That’s it. Now we only have to check whether it was “our” enter key or another key we are not interested in:

  1. if((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return))
  2. {
  3.     //Enter or return was pressed
  4. }
  5. else
  6. {
  7.     return QObject::eventFilter(obj, event);
  8. }
  9. return true;

Finally, we can install our event handler:

  1. keyEnterReceiver *key = new keyEnterReceiver();
  2. aWidgetInAnotherClass->installEventFilter(key);

Categories: