qt 定时器任务在多线程中执行


 

#include <QTimer>
#include <QMutex> //多线程
#include <QThread>

 

 

    QThread* plantimer_thread = new QThread(this);
    QTimer* plantimer = new QTimer();
    plantimer->moveToThread(plantimer_thread);
    plantimer->setInterval(1500);
    //connect(plantimer_thread,&QThread::start, plantimer,&QTimer::start);//通过线程开启来触发定时器开启
    connect(plantimer_thread, SIGNAL(started()), plantimer, SLOT(start()));//通过线程开启来触发定时器开启
    connect(plantimer, &QTimer::timeout, this, &MainWindow::timerAutoSendSlots, Qt::DirectConnection);//信号发出后立即调用槽函数,槽函数在发出信号的线程中执行
    connect(plantimer_thread, &QThread::finished, this, &QObject::deleteLater);//线程结束,自动关闭线程
    plantimer_thread->start();



void MainWindow::timerAutoSendSlots()
{
    qDebug() << QStringLiteral("当前线程id:") << QThread::currentThread();
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM