QT启动新线程执⾏QTimer
编写QT程序时,时常会需要使⽤定时器QTimer来执⾏⼀些定时任务,但当定时任务执⾏的时间过长,则会影响整个界⾯的响应,因此会想到使⽤另⼀个⼯作线程来执⾏定时器,⼀般情况下可以选择从QThread派⽣⼀个线程类,然后重载run并执⾏任务逻辑,那下⾯就介绍⼀个不⽤从QThread派⽣并使⽤QTimer的例⼦。
1.主窗⼝类头⽂件加⼊:
_voiceThread = new QThread;
_voiceTimer = new QTimer;
2.构造函数加⼊:
_voiceThread = new QThread;
_voiceTimer = new QTimer;
_voiceTimer->setSingleShot(true); //定时器单次处罚
/
* 在moveToThread前先启动定时器,不然不在⼀个线程⾥,直接调⽤start会失败 */
_voiceTimer->start(200);
_voiceTimer->moveToThread(_voiceThread);
/* 定时器对象和this不在⼀个线程⾥⾯,因此这边指定了连接⽅式为Qt::DirectConnection,由定时器所在线程直接触发_onVoiceTimeout */
connect(_voiceTimer, SIGNAL(timeout()), this, SLOT(_onVoiceTimeout()), Qt::DirectConnection);
/* 连接定时器槽,⽤来停⽌定时器 */
connect(this, SIGNAL(stop()), _voiceTimer, SLOT(stop()));
/* 启动线程 */
_voiceThread->start();
3.析构函数加⼊:
emit stop();
_voiceThread->quit();
_voiceThread->wait();
delete _voiceTimer;
delete _voiceThread;
4.定时器槽:
void Test::_onVoiceTimeout()
{
// 执⾏任务
// ...
_voiceTimer->start(1000);
}
注: 第⼆次启动定时器的时候,发现没有触发槽函数,,,需要重新 new + connecttimeout on t2 timer
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论