在类定义public中添加
QThread* _TimerThread; QTimer* _WriteTimer; void WriteTimestop();
在private slot中添加
void _onWriteTimeout();
构造函数中添加:
// 使用一个线程,跑定时器 _TimerThread = new QThread; _WriteTimer = new QTimer; // _WriteTimer->setSingleShot(true); //千万不要添加这一行,添加后新线程只运行一下就结束了,造成定时器只会触发一次timeout // 在moveToThread前先启动定时器,不然不在一个线程里,直接调用start会失败 _WriteTimer->start(2000); _WriteTimer->moveToThread(_TimerThread); // 定时器对象和this不在一个线程里面,因此这边指定了连接方式为Qt::DirectConnection,由定时器所在线程直接触发_onVoiceTimeout connect(_WriteTimer, SIGNAL(timeout()), this, SLOT(_onWriteTimeout()), Qt::DirectConnection); // 连接定时器槽,用来停止定时器 connect(this, SIGNAL(WriteTimestop()), _WriteTimer, SLOT(stop())); _TimerThread->start();在析构函数中添加:
emit WriteTimestop(); _TimerThread->quit(); _TimerThread->wait(); delete _WriteTimer; delete _TimerThread;
转载自:http://blog.csdn.net/xwdpepsi/article/details/8607496