Search code examples
multithreadingqtqt5qtimer

Why is a call to QTimer::start() outside a QThread (event loop) not failing?


The documentation says

In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.

So I'd expect this code...

int main(int argc, char *argv[])
{
  QCoreApplication app(argc, argv);
  QTimer timer;
  timer.start(1000);

  app.exec();

}

...to fail because the main thread, where I'm calling start, is not a QThread and Timers can only be used with threads started with QThread

QUESTION

Why doesn't this fail?


Solution

  • It seems that you have not understood correctly what the documentation indicates, let's analyze each part of the statement:


    In multithreaded applications, you can use QTimer in any thread that has an event loop.

    Where did you use the QTimer is there an event loop? Yes, you are using the QTimer in the main thread and you have created the event loop through the QXApplication.

    To start an event loop from a non-GUI thread, use QThread::exec()

    Is the main thread a non-GUI thread? No, so it is not necessary in this case to use QThread to use a QTimer in the main thread.

    In what cases can QTimer fail? If the QTimer runs in the main thread and you have not created a QXApplication, or if you run it in a thread where there is no Qt event loop as std::thread.


    Conclusion:

    If the QTimer is used in the main thread, just run the QXApplication, if you want to use it in another thread then you must use QThread. In other words, QTimer only works if there is a Qt event loop.