定时器在编程中经常要用到,有必要学习一下,记记笔记!

Qt中定时器的使用有两种方法,一种是使用QObject类提供的定时器,还有一种就是使用QTimer类。

1、QObject中的定时器的使用,需要用到三个函数

int QObject::startTimer ( int interval ) ;          // 开启定时器并设定间隔,返回定时器ID

void QObject::timerEvent ( QTimerEvent * event );     // 定时器到时处理函数

void QObject::killTimer ( int id );             // 关闭定时器

2、使用QTimer定时器类(可以使用信号与槽)

QTimer *timer = new QTimer(this);              // 设置定时器

connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));   // 连接定时器到时槽函数

void QTimer::start ( int msec );                 // 开启定时器并设定间隔

void QTimer::stop();                    // 关闭定时器

关于定时器精度:

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

void QTimer::setTimerType(Qt::TimerType atype);

Qt Assitant中的原文如下:

enum Qt::TimerType

The timer type indicates how accurate a timer can be.

QTimerDisplay.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 
#ifndef QTIMERDISPLAY_H
#define QTIMERDISPLAY_H

#include <QObject>
#include <QTimer>
#include <QTimerEvent>
#include <QDebug>

class QTimerDisplay : public QObject
{
    Q_OBJECT
public:
    explicit QTimerDisplay(QObject *parent = nullptr);

protected:
    // ![0]
    virtual void timerEvent(QTimerEvent *event);
    // ![0]

signals:

public slots:
    // ![1]
    void onTimeout();
    // ![1]

private:
    // ![0]
    int     m_nTimerID;
    // ![0]
    // ![1]
    QTimer  *m_pTimer;
    // ![1]
};

#endif // QTIMERDISPLAY_H

QTimerDisplay.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 
#include "qtimerdisplay.h"

)

QTimerDisplay::QTimerDisplay(QObject *parent) : QObject(parent)
{
    // ![0]
    m_nTimerID = startTimer(TIMER_TIMEOUT);
    // ![0]
    // ![1]
    m_pTimer = new QTimer(this);
    connect(m_pTimer, SIGNAL(timeout()), this, SLOT(onTimeout()));
    m_pTimer->start();
    // ![1]
}

// ![0]
void QTimerDisplay::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == m_nTimerID)
    {
        qDebug() << "Timer ID:" << event->timerId();
    }
}
// ![0]

// ![1]
void QTimerDisplay::onTimeout()
{
    qDebug() << "Timer is out!";
}
// ![1]

最新文章

  1. iOS chart 图表完美解决方案 基于swift
  2. js跨域那些事
  3. 《CDN技术详解》 - CDN知多少?
  4. Unity3d 枚举某个目录下所有资源
  5. python mysql desc
  6. C语言 百炼成钢17
  7. VBS基础篇 - 过程(sub 与 Function)
  8. Arrays类的十大用法
  9. 使用HTTP协下载文件
  10. DownloadProvider调试
  11. 自己主动生成材质Material(Unity3D开发之十九)
  12. APP设计规范大全
  13. CSS3 布局
  14. linux下用script和scriptreplay对命令行操作录像
  15. TJOI2015 day1解题报告
  16. [解读REST] 5.Web的需求 &amp; 推导REST
  17. vscode编辑器自动生成.vue文件
  18. python基础之 编码进阶,文件操作和深浅copy
  19. openstack网络
  20. elasticsearch6.7 05. Document APIs(10)Reindex API

热门文章

  1. Java中LinkedList实现原理
  2. adc 测量子系统
  3. for语句练习 阶乘
  4. opencv 中affine函数实现旋转和平移
  5. hbase源码系列(一)Balancer 负载均衡
  6. 批量设置ssh无密码登陆脚本
  7. iptables nat 外网nat到内网在只限制外网访问的单一ip地址
  8. WebForm发送邮件
  9. eclipse配置代码自动提示
  10. Linux系统下邮件服务器的搭建(Postfix+Dovecot)