How to run a timer inside a QThread?

前端 未结 4 1368
长情又很酷
长情又很酷 2020-12-30 15:52

I would like to run a timer inside a QThread. I have written some code in which i am getting some error during the run time. Please guide me into the right direction. What a

4条回答
  •  生来不讨喜
    2020-12-30 16:32

    I was able to create a simple example that starts a timer within another thread, using lambda functions. Here is the code:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    int main(int argc, char** argv)
    {
        QCoreApplication app(argc, argv);
        QThread* thread = new QThread(&app);
        QObject::connect(thread, &QThread::started, [=]()
        {
            qInfo() << "Thread started";
            QTimer* timer1 = new QTimer(thread);
            timer1->setInterval(100);
            QObject::connect(timer1, &QTimer::timeout, [=]()
            {
                qInfo() << "Timer1 " << QThread::currentThreadId();
            });
            timer1->start();
        });
        thread->start();
    
        QTimer timer2(&app);
        QObject::connect(&timer2, &QTimer::timeout, [=]()
        {
            qInfo() << "Timer2 " << QThread::currentThreadId();
        });
        timer2.setInterval(100);
        timer2.start();
    
        return app.exec();
    }
    

提交回复
热议问题