Starting QTimer In A QThread

前端 未结 6 2252
醉梦人生
醉梦人生 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 11:48

    You need an event loop to have timers. Here's how I solved the same problem with my code:

    MyThread::MyThread() {
    }
    
    void MyThread::run() {
        QTimer* timer = new QTimer(this);
        timer->setInterval(1);
        timer->connect(timer, SIGNAL(timeout()), this, SLOT(doIt()));
        timer->start();
    
        /* Here: */
        exec();             // Starts Qt event loop and stays there
       // Which means you can't have a while(true) loop inside doIt()
       // which instead will get called every 1 ms by your init code above.
    }
    
    void MyThread::doIt(){
        cout << "it works";
    }
    

    Here's the relevant piece of the documentation that none of the other posters mentioned:

    int QCoreApplication::exec()

    Enters the main event loop and waits until exit() is called. Returns the value that was set to exit() (which is 0 if exit() is called via quit()). It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets. To make your application perform idle processing (i.e. executing a special function whenever there are no pending events), use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().

提交回复
热议问题