Qt的三种定时器的使用

1、singleShot

原型:void QTimer::singleShot(int msec, const QObject *receiver, const char *member)

解释:这个静态函数在一个给定时间间隔 msec(毫秒) 之后调用一个槽。

用法1 :
假设类A有个槽函数 function() { }
我们要在1s之后执行它

QTimer::singleShot(1000,this, &A::function());

用法2:
实现循环
槽函数中还是singleShot 即:

//这样的话就是一个每1秒执行一次的定时器
bool
condition = true; function(){ if(condition){ //条件控制 QTimer::singleShot(1000,this, &A::function()); } }

2、timerEvent

函数原型:[virtual protected] void QObject::timerEvent(QTimerEvent *event)

解释:QObject提供的定时器通过startTimer(int interval)启动,该函数启动了一个时间间隔为interval毫秒的定时器,启动成功只返回一个定时器标志符,失败返回0,因为只返回一个标志符,所以无法获得该定时器的对象,它是QObject的成员函数,及不能正常的使用信号与槽,只能通过重载定时器事件处理函数timerEvent,在里面写定时器触发要做的事。

如果有多个定时器,可以通过QTimerEvent::timerId()来获取已经启动的定时器标识符。

该定时器只能通过killTimer(int id)杀死,参数id为之前生成定时器标志符,根据标志符杀死定时器。

void QObject::killTimer(int id); 

每一个定时器做的事情可能不一样,但是定时器处理函数只有一个,我们可以通过if判断来让某个定时器干某件事

class MyObject : public QObject
  {
      Q_OBJECT
 
  public:
      MyObject(QObject *parent = 0);
 
  protected:
      //重写定时器事件
      void timerEvent(QTimerEvent *event);
  
  private//声明定时器ID
      int timeID; 
  };
 
  MyObject::MyObject(QObject *parent)
      : QObject(parent)
  {
      timeID = startTimer(1000);   // 1-second timer
  }
 
  void MyObject::timerEvent(QTimerEvent *event)
  {
      qDebug() << "Timer ID:" << event->timerId();
      
      if(event->timerId() == timeID)
      {
          //todo function
          if(timeID)
          {
              killTimer(timeID);// 杀死定时器
          }
          timeID = 0;
      }
  }

3、QTimer类定时器

使用QTimer类定时器的步骤:

(1)先创建一个QTimer定时器实例:QTimer *timer = new QTimer(this);

(2)然后连接超时信号与槽:connect(timer, SIGNAL(timeout()), this, SLOT(Func()));

(3)设置定时器触发间隔(设置触发间隔有两个方法,一个是调用setInterval(int msec)设置,另一个是调用start(int msec)时可将间隔时间作为参数):

void setInterval(int msec) ;,

(4)在需要的地方启动定时器:start(),或者设间隔时间,可通过start(1000),即启动一个1000毫秒的定时器

(5)用完了暂停定时器:stop();

(6)删除定时器实例:delete timer;

参考链接:https://blog.csdn.net/ddllrrbb/article/details/88810767

     https://blog.csdn.net/kidults/article/details/80091788

原文地址:https://www.cnblogs.com/kongbursi-2292702937/p/15080135.html