让QTimer 跑在其他线程. 一般写法如下.
1. 在main thread中为worker thread指定定时器.
QThread* thread = new QThread(this);
thread->start();
QTimer *timer = new QTimer(0);
timer->setInterval(100);
timer->moveToThread(thread);
connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()), Qt::DirectConnection);
connect(thread, SIGNAL(started()), timer,SLOT(start()));
需要注意几个地方.
1) QTimer 不能指定parent, 否则 会出现警告 " QObject::moveToThread: Cannot move objects with a parent"
因为moveToThread 无法移动有parent的object.
2) QTimer 需要用moveToThread 来改变线程相关性. 这样emit signal的时候才会在worker线程.
3) connect timeout时, 需要附加参数Qt::DirectConnection,
根据Qt的文档中
Qt::AutoConnection 0 (default) If the signal is emitted fro