QTimer to execute method every second

前端 未结 3 1008
醉酒成梦
醉酒成梦 2020-12-22 02:05

I\'m learning Qt and I was reading about Threads, Events and QObjects from Qt wiki, and followed the wiki recommendations on how to handle some work in a while condition but

3条回答
  •  长情又很酷
    2020-12-22 02:37

    You don't declare the timer neither the slot. In the header you must declare:

    class ... {
    
      QTimer timer;
      ...
    private slots:
      void processMessages();
      ...
    };
    

    Then remember to make the SIGNAL-SLOT connection and configure the timer:

    connect(&timer, SIGNAL(timeout()), this, SLOT(processMessages()));
    timer.setInterval(1000);
    timer.start();
    

    Also timer.start(1000); would be valid...

    ANOTHER POSSIBILITY

    Other possibility would be to use the timer associated with each Q_OBJECT and overload the timerEvent:

    class ... {
      Q_OBJECT
      ...
    protected:
      void timerEvent(QTimerEvent *event);
      ...
    };
    

    Then you must implement the timer event as this:

    void MyClass::timerEvent(QTimerEvent *event) {
      processMessages();
    }
    

    And you can configure the timer with a simple call to startTimer(1000);

提交回复
热议问题