问题
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