'Qt Widget - how to capture just a few keyboard keys

I know that with grabKeyboard() my widget is able to grab every keyboard event also if it's not focused, but what if I wanted to capture just three or four keys?

I tried with an event filter https://doc.qt.io/qt-5/qobject.html#installEventFilter

but that didn't work (perhaps because I installed it like this?)

 class MyWidget: public QGLWidget
    {
        ...
    protected:
        bool eventFilter( QObject *o, QEvent *e );
    };

    bool MyWidget::eventFilter( QObject *o, QEvent *e )
    {
        if ( e->type() == QEvent::KeyPress ) {
            // special processing for key press
            QKeyEvent *k = (QKeyEvent *)e;
            qDebug( "Ate key press %d", k->key() );
            return TRUE; // eat event
        } else {
            // standard event processing
            return FALSE;
        }
    }

// Installed it in the constructor
MyWidget::MyWidget()
{
    this->installEventFilter(this);
}

How can I intercept just a few keys in my widget and leave other widgets (QTextEdits) the rest?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source