Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt Widget - how to capture just a few keyboard keys

Tags:

c++

keyboard

qt4

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?

like image 338
Johnny Pauling Avatar asked Jul 23 '12 18:07

Johnny Pauling


1 Answers

Your own comment says it all:

return TRUE; // eat event

As you return true for all keys, the event won't be further processed. You must return false for all keys you don't want to handle.

Another way without event filter but reimplementing keyPressEvent:

void MyWidget::keyPressEvent( QKeyEvent* event ) {
    switch ( event->key() ) {
    case Qt::Key_X:
        //act on 'X'
        break;
    case Qt::Key_Y:
        //act on 'Y'
        break;
    default:
        event->ignore();
        break;
    }
}
like image 120
Frank Osterfeld Avatar answered Oct 01 '22 00:10

Frank Osterfeld