Solved How can I check if the Shift key is pressed in Qt in real time?
-
I have a
QTimer
object and I need to test if the Shift key is pressed in Qt every 30 milliseconds. I tried to useif(QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier))
:QObject::connect(timer, &QTimer::timeout, [=](){ if(QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)){ //Do stuff } else{ //Do something different } }
The problem is that the result of the
QGuiApplication::keyboardModifiers()
isn't updated very often. After some testing, I noticed that it only updates when I press another key. So I tried to simulate pressing the Enter key:QKeyEvent *event = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier); QCoreApplication::postEvent(someWidget, event);
This didn't change anything.
I would like a working way of checking in real time if the Shift key is pressed. I can't use events because I need this to work no matter what widget is visible. Any solution?
-
@Donald-Duck said in How can I check if the Shift key is pressed in Qt in real time?:
I need this to work no matter what widget is visible. Any solution?
Hi
I was wondering if an event filter would work for you ?
http://doc.qt.io/qt-4.8/eventsandfilters.html#event-filters
You still have to install it to the widgets but no subclassing or extra code is otherwise
needed. -
No, it doesn't work. I tried the following code to see if it works:
bool SomeWidget::eventFilter(QObject *watched, QEvent *event){ QMessageBox::information(NULL, "", ""); return true; }
As far as I've understood, the above code is supposed to open a message box whenever an event is triggered, but it doesn't do anything. I also tried with
return false
, but with no success. What's the problem? -
@Donald-Duck
Did you assign/ install it on the widgets ?
http://doc.qt.io/qt-4.8/qobject.html#installEventFilterhttp://www.informit.com/articles/article.aspx?p=1405544&seqNum=2
-
@mrjj Thanks, it worked.
-
You don't need to do all that. Use QGuiApplication::queryKeyboardModifiers() instead of
QGuiApplication::keyboardModifiers()
.