编写QT程序时,时常会需要使用定时器QTimer来执行一些定时任务,但当定时任务执行的时间过长,则会影响整个界面的响应,因此会想到使用另一个工作线程来执行定时器,一般情况下可以选择从QThread派生一个线程类,然后重载run并执行任务逻辑,那下面就介绍一个不用从QThread派生并使用QTimer的例子。
主窗口类头文件加入:
[cpp] view plain copy
QThread* _voiceThread;
QTimer* _voiceTimer;
构造函数加入:
[cpp] view plain copy
_voiceThread = new QThread;
_voiceTimer = new QTimer;
_voiceTimer->setSingleShot(true);
_voiceTimer->start(200);
_voiceTimer->moveToThread(_voiceThread);
connect(_voiceTimer, SIGNAL(timeout()), this, SLOT(_onVoiceTimeout()), Qt::DirectConnection);
connect(this, SIGNAL(stop()), _voiceTimer, SLOT(stop()));
_voiceThread->start();
析构函数加入:
[cpp] view plain copy
emit stop();
_voiceThread->quit();
_voiceThread->wait();
delete _voiceTimer;
delete _voiceThread;
定时器槽:
[cpp] view plain copy
void Test::_onVoiceTimeout()
{
_voiceTimer->start(1000);
}