Qt Widget - how to capture just a few keyboard keys

不羁岁月 提交于 2021-02-07 14:16:49

问题


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 http://doc.trolltech.com/3.3/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?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/11618664/qt-widget-how-to-capture-just-a-few-keyboard-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!