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
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With