为何主线程调用QTimer::start()未失败?(疑与Qt文档描述冲突)
Great question! Let's break down why your code works perfectly, even though it seems to clash with your initial understanding of QThread and QTimer.
First, let's clear up a key misunderstanding: the main thread of your Qt application is already a QThread instance—you just don't create it explicitly. When you initialize QCoreApplication (or QApplication for GUI apps), Qt automatically wraps the program's main thread into a QThread object. You can even verify this by adding qDebug() << QThread::currentThread(); to your main function—you'll see it outputs a valid QThread pointer.
Now let's tie this back to the Qt documentation you referenced:
QTimer can be used in any thread that has an event loop. To start an event loop in a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Therefore, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.
Your main thread checks all these boxes:
- It has an event loop: You start it with
app.exec()—this is exactly what processes timer events (along with other events like signals and slots). - The timer's thread affinity is the main thread: Your
QTimer timeris created in the main thread, so it's bound to this thread by default. - You start the timer in its own thread:
timer.start(1000)is called directly in the main thread, which complies with the "start/stop in its thread" rule.
Your initial thought that QTimer only works with threads created via QThread is incorrect. The docs specify "any thread that has an event loop"—the main thread is just as valid as any worker thread you create with QThread (as long as you start the event loop in those workers with QThread::exec()).
As a quick test, if you removed app.exec() from your code, the timer would never trigger—because there's no event loop running to handle the timer's timeout events. That's a good way to confirm the event loop's critical role here.
内容的提问来源于stack exchange,提问作者Bob

