Starting QTimer In A QThread

前端 未结 6 2250
醉梦人生
醉梦人生 2020-12-01 11:05

I am trying to start a QTimer in a specific thread. However, the timer does not seem to execute and nothing is printing out. Is it something to do with the timer, the slot o

6条回答
  •  悲&欢浪女
    2020-12-01 12:01

    I have created an example that calls the timer within a lambda function:

    #include 
    #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();
    }
    

提交回复
热议问题