Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c++ - Qt multiple key combo event

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 the time, just the same way as it works with single key events. I tried to use QShortcuts and enable autorepeat for them, but that didn't work:

keyCombos_.push_back(new QShortcut(QKeySequence(Qt::Key_W, Qt::Key_D), this));
connect(keyCombos_[0], SIGNAL(activated()), SLOT(keySequenceEvent_WD()));
setShortcutAutoRepeat(keyCombos_[0]->id(), true);

When using this approach I also have the problem that I can't catch single Key_W (or whatever the first Key in the keysequence is) strokes anymore.

Thanks, Thomas

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<int> 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();

        if ( 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...