QTimer对象的 start 函数调用必须和创建QTimer对象是同一个线程。
#include "QtTimerTest.h"
#include <QDebug>QtTimerTest::QtTimerTest(QWidget *parent): QMainWindow(parent),m_timer(nullptr),m_timerThread(nullptr), m_workingThread(nullptr)
{ui.setupUi(this);m_timer = new QTimer;connect(m_timer, &QTimer::timeout, this, &QtTimerTest::slot_timeOut);m_workingThread = new WorkingThread(m_timer);m_workingThread->start();
}QtTimerTest::~QtTimerTest()
{}void QtTimerTest::slot_timeOut()
{qDebug() << "timer thread id : " << QThread::currentThreadId();
}
#include "WorkingThread.h"
#include <QDebug>WorkingThread::WorkingThread(QTimer* timer):m_timer(timer)
{}void WorkingThread::run()
{qDebug() << "WorkingThread::run() thread id : " << QThread::currentThreadId();if (nullptr != m_timer){m_timer->start(1000);}
}
如果 QTimer 对象和start()函数处于同一个线程则不会有问题