如何在子线程中启动定时器:
MyThread::MyThread(QObject *parent) : QThread(parent) { printf("[%d] construct\n",this->currentThreadId()); } MyThread::~MyThread() { delete timer; } void MyThread::timedone() { printf("[%d] test...\n",this->currentThreadId()); } void MyThread::run() { printf("[%d] sub thread start\n",this->currentThreadId()); timer = new QTimer(); connect(timer,SIGNAL(timeout()),this,SLOT(timedone()),Qt::DirectConnection); timer->start(2000); exec(); }
如上:在线程run中创建QTimer,使用DirectConnection连接槽函数,然后启动qt消息循环exec,输出如下:
[5980] main thread start [5980] construct [5516] sub thread start [5516] test... [5516] test... [5516] test... [5516] test... [5516] test... [5516] test... [5516] test...
1.如果QTimer传入this指针,输入如下:
[7616] main thread start [7616] construct [7380] sub thread start QObject: Cannot create children for a parent that is in a different thread. (Parent is MyThread(0xe2b010), parent's thread is QThread(0x7debf8), current thr ead is MyThread(0xe2b010) [7380] test... [7380] test... [7380] test...
虽然也能正常运行,但会提示一个警告(算是):cannot create child for a parent,不能为一个父对象创建一个子对象在不同的线程,应该是创建了,但没有关联上父对象而已(所以应该在析构函数中delete),对么。
2.将DirectConnection去掉,输出如下:
[4036] main thread start [4036] construct [7580] sub thread start [4036] test... [4036] test... [4036] test... [4036] test... [4036] test...
输出还在主线程中
3.将exec换成其他比如while(1),信号槽能正常连接,但永远不会调用超时函数timedone,信号其实是消息,走qt消息循环吧
[6020] main thread start [6020] construct [1244] sub thread start