Qt Widget-如何仅捕获几个键盘键 [英] Qt Widget - how to capture just a few keyboard keys

查看:78
本文介绍了Qt Widget-如何仅捕获几个键盘键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果没有重点关注,只要使用grabKeyboard(),我的小部件就可以捕获每个键盘事件,但是如果我只想捕获三个或四个键怎么办?

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?

我尝试使用事件过滤器 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);
}

我如何才能仅拦截窗口小部件中的几个键,而将其余的窗口小部件(QTextEdits)保留下来?

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

推荐答案

您自己的评论说明了一切:

Your own comment says it all:

return TRUE; // eat event

当您为所有键返回 true 时,该事件将不会得到进一步处理.您必须为所有不想处理的键返回 false .

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.

没有事件过滤器但重新实现keyPressEvent的另一种方法:

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

这篇关于Qt Widget-如何仅捕获几个键盘键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆