Qt multiple key combo event

前端 未结 2 1630
闹比i
闹比i 2020-12-18 06:01

I\'m using Qt 4.6 and I\'d like to react to multi-key combos (e.g. Key_Q+Key_W) that are being held down. So when you hold down a key combo, the event should be called all t

2条回答
  •  长情又很酷
    2020-12-18 06:36

    You can add a pressed key to the set of pressed keys and remove from this set when the key is released. So you can add the pressed key to a QSet which is a class member :

    QSet pressedKeys;
    

    You can catch the key events in an event filter :

    bool MyWidget::eventFilter(QObject * obj, QEvent * event)
    {
    
        if(event->type()==QEvent::KeyPress) {
    
            pressedKeys += ((QKeyEvent*)event)->key();
    
            f( pressedKeys.contains(Qt::Key_D) && pressedKeys.contains(Qt::Key_W) )
            {
                // D and W are pressed
            }
    
        }
        else if(event->type()==QEvent::KeyRelease)
        {
    
            pressedKeys -= ((QKeyEvent*)event)->key();
        }
    
    
        return false;
    }
    

    Don't forget to install the event filter in the constructor:

    this->installEventFilter(this);
    

提交回复
热议问题