QTimer and the thread of the Qt loop
-
Hello,
I was told in the past that if a QTimer is connected to a particular slot (that is called whenever the signaltimeout()
happens), that QTimer is still processed in the same thread that the Qt loop is. However, in order to verify that, I connected a QPushButton to another slot that callsQMessageBox::question(...)
somewhere inside. When I triggered that slot, I was shocked to see that the QTimer kept on doing its work. But in this case, isn't the Qt loop "frozen" for as long as I don't close the QMessageBox? Isn't it blocked at my slot, waiting forQMessageBox::question(...)
to return something?Thanks in advance for enlightening me.
-
@Pippin said in QTimer and the thread of the Qt loop:
in this case, isn't the Qt loop "frozen" for as long as I don't close the QMessageBox? Isn't it blocked at my slot, waiting for
QMessageBox::question(...)
to return something?QMessageBox::question()
blocks your calling function, but it also starts another event loop.This new event loop allows the
QMessageBox
to handle mouse events (so that you can click the buttons in theQMessageBox
). It also allows theQTimer
to continue working. -
@JKSH said in QTimer and the thread of the Qt loop:
This new event loops [...] allows the
QTimer
to continue working.I don't think it needs an event loop at all, just a running thread, for example:
#include <QTimer> #include <QCoreApplication> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QTimer aTimer; aTimer.setInterval(1000); aTimer.setSingleShot(true); aTimer.start(); while (true) { qDebug() << aTimer.remainingTime(); } return 0; }
works fine. the event loop is required only as a bridge between signals and slots
-
@VRonin said in QTimer and the thread of the Qt loop:
the event loop is required only as a bridge between signals and slots
That's right.
The original question was: How could the QTimer's
timeout()
signal continue getting processed whenQMessageBox::question()
is blocking the thread?The answer is: Because the block is caused by a new event loop (started by
QDialog::exec()
if I'm not mistaken). This event loop processes the QTimer's signals, even though the calling function is still blocked. -
@JKSH said in QTimer and the thread of the Qt loop:
started by QDialog::exec() if I'm not mistaken
You're not. All the message box statics call
QDialog::exec
, which in turn callsQEventLoop::exec
.