Qt 不一样的定时器

Qt中定时器一般使用QTimer:

Qtimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);

今天偶然发现了另外一种定时器,原型如下:

int QObject::startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer)

使用详情可以在Qt手册中查看
要想使用startTimer(),类必须继承自QObject且在类中重新实现QObject::timerEvent(),例如:

class MyObject : public QObject
  {
      Q_OBJECT

  public:
      MyObject(QObject *parent = 0);

  protected:
      void timerEvent(QTimerEvent *event);
  };

  MyObject::MyObject(QObject *parent)
      : QObject(parent)
  {
      startTimer(50);     // 50-millisecond timer
      startTimer(1000);   // 1-second timer
      startTimer(60000);  // 1-minute timer

      using namespace std::chrono;
      startTimer(milliseconds(50));
      startTimer(seconds(1));
      startTimer(minutes(1));

      // since C++14 we can use std::chrono::duration literals, e.g.:
      startTimer(100ms);
      startTimer(5s);
      startTimer(2min);
      startTimer(1h);
  }

  void MyObject::timerEvent(QTimerEvent *event)
  {
      qDebug() << "Timer ID:" << event->timerId();
  }

以上示例来自Qt官方文档
此处可以发现timerEvent()中输出了一个event->timeId()
timeIdstartTimer()函数的返回值。
上边例子稍微修改一下:

class MyObject : public QObject
  {
      Q_OBJECT

  public:
      MyObject(QObject *parent = 0);

  protected:
      void timerEvent(QTimerEvent *event);
  private:
      int firstTimer;
      int secondTimer;
      int thirdTimer;

  };

  MyObject::MyObject(QObject *parent)
      : QObject(parent)
  {
      firstTimer=startTimer(50);     // 50-millisecond timer
      secondTimer=startTimer(1000);   // 1-second timer
      thirdTimer=startTimer(60000);  // 1-minute timer

      using namespace std::chrono;
      startTimer(milliseconds(50));
      startTimer(seconds(1));
      startTimer(minutes(1));

      // since C++14 we can use std::chrono::duration literals, e.g.:
      startTimer(100ms);
      startTimer(5s);
      startTimer(2min);
      startTimer(1h);
  }

  void MyObject::timerEvent(QTimerEvent *event)
  {
      qDebug() << "Timer ID:" << event->timerId();
      int timerId = event->timerId();
      switch(timerId)
      {
      case firstTimer:
          qDebug()<<"firstTimer:"<<timerId;
          break;
      case secondTimer:
          qDebug()<<"secondTimer:"<<timerId;
          break;
      case thirdTimer:
          qDebug()<<"thirdTimer:"<<timerId;
          break:
	  }
  }

有了定时器的创建与响应,还需要结束,传入startTimer()的返回值即可结束定时器。

void QObject::killTimer(int id)

总结:调用QObject::startTimer()实现的定时器集中在timerEvent()函数中处理,这种方式适合在整个程序生命周期中定时做任务的情况,例如,上位机轮询下位机运行情况、客户端定时请求服务端消息等

你可能感兴趣的:(qt,Qt,定时器)