Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt multiple key combo event

Tags:

c++

key

events

qt

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

like image 510
user364688 Avatar asked Jun 20 '10 21:06

user364688


2 Answers

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);
like image 172
Nejat Avatar answered Oct 07 '22 13:10

Nejat


QShortcut does not support the functionality you're looking for. You can only make combinations with modifier keys like Shift, Ctrl, Alt and Meta.

What your code does is to make a shortcut that responds when the user first presses W and then D. This is also why it will conflict with other shortcuts that respond to just W.

When you want to do something when both W and D are pressed at the same time, you'll have to override QWidget's keyPressEvent and keyReleaseEvent methods in order to keep track of their pressed state, and manually call your handler function once they are both pressed. If you don't have a suitable QWidget subclass in use you'd either have to introduce it, or install an event filter in the right place using QObject::installEventFilter, possibly on your application object if it's supposed to be a global shortcut.

like image 44
Thorbjørn Lindeijer Avatar answered Oct 07 '22 15:10

Thorbjørn Lindeijer