为什么在 QThread(事件循环)之外调用 QTimer::start() 不会失败?

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

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.

所以我希望这段代码...

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

  app.exec();

}

...失败,因为我调用 start 的主线程不是 QThread

问题

为什么这没有失败?

看来你没有正确理解文档的意思,我们来分析一下语句的各个部分:


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

你在哪里使用QTimer有事件循环吗?是的,你在主线程中使用QTimer并且你已经通过QXApplication创建了事件循环。

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

主线程是非GUI线程吗?不是,所以在这种情况下使用QThread在主线程中使用一个QTimer是没有必要的。

在什么情况下 QTimer 会失败? 如果主线程中的 QTimer 运行s 而你还没有创建 QXApplication,或者如果你 运行 它在没有 Qt 事件循环的线程中,如 std::thread.


结论:

如果在主线程中使用QTimer,则运行QXApplication,如果要在另一个线程中使用它,则必须使用QThread。换句话说,QTimer 只有在有 Qt 事件循环的情况下才有效。