QT 中 QTimer 类 备查

基础

cpp 复制代码
// 指定了父对象, 创建的堆内存可以自动析构
QTimer::QTimer(QObject *parent = nullptr);

// 根据指定的时间间隔启动或者重启定时器, 需要调用 setInterval() 设置时间间隔
void QTimer::start();

// 启动或重新启动定时器,超时间隔为msec毫秒。
void QTimer::start(int msec);

// 停止定时器。
void QTimer::stop();

//当定时器超时时,该信号就会被发射出来。
[signal] void QTimer::timeout();

// 设置定时器时间间隔为 msec 毫秒,默认值是0。
void QTimer::setInterval(int msec);

// 获取定时器的时间间隔, 返回值单位: 毫秒
int QTimer::interval() const;

设置定时器精度

cpp 复制代码
void QTimer::setTimerType(Qt::TimerType atype);	// 设置定时器的精度
参数: 
    - Qt::PreciseTimer -> 精确的精度, 毫秒级
    - Qt::CoarseTimer  -> 粗糙的精度, 和1毫秒的误差在5%的范围内, 默认精度
    - Qt::VeryCoarseTimer -> 非常粗糙的精度, 精度在1秒左右

Qt::TimerType QTimer::timerType() const;	// 获取当前定时器的精度
在这里插入代码片

其他API

cpp 复制代码
// 如果定时器正在运行,返回true; 否则返回false。
bool QTimer::isActive() const;

// 判断定时器是否只触发一次
bool QTimer::isSingleShot() const;

// 设置定时器是否只触发一次, 参数为true定时器只触发一次, 为false定时器重复触发, 默认为false
void QTimer::setSingleShot(bool singleShot);

小案列1

效果
思路
cpp 复制代码
    //设置界面实时时间
    QTimer *timer = new QTimer(this);
    timer->start(1000);//启动定时器
    connect(timer, &QTimer::timeout, [=](){
        QTime time = QTime::currentTime();//获取当前时间
        QString str = time.toString("hh:mm:ss");
        ui->label_curTime->setText(str);//显示到界面
    });

小案列2

使用QTimer类中的 全局静态 函数,实现延时。

cpp 复制代码
[static] void QTimer::singleShot(int msec, const QObject *receiver, PointerToMemberFunction method);
功能: 在 msec 毫秒后发射一次信号, 并且只发射一次
参数:
	- msec:     在msec毫秒后发射信号
	- receiver: 接收信号的对象地址
	- method:   槽函数地址
思路
cpp 复制代码
//延时300毫秒,切换窗口
QTimer::singleShot(300, this, [=](){// 延时300毫秒
    this->hide();//隐藏主窗口
    chooseScene->show();//显示其他窗口
});

其他方法使用定时器

返回定时器 Id

重写定时器事件,利用 定时器 id 判断是哪一个定时器

详细教程可转

爱编程的大丙

相关推荐
2739920295 小时前
AES加解密(QT)
qt
颜*鸣&空15 小时前
QT实现串口通信+VSPD+串口调试工具
开发语言·qt
颜*鸣&空20 小时前
QT程序实现串口通信案例
开发语言·qt
Main. 2420 小时前
从0到1学习Qt -- 常见控件之显示类控件
qt·学习
qq_401700411 天前
Qt中事件循环与并发机制的协同工作
qt
qq_401700412 天前
Qt Positioning 模块访问设备地理位置信息
开发语言·qt
闫有尽意无琼2 天前
银河麒麟v11 arm编译Qt creator8.0.2报错
开发语言·qt
lqj_本人2 天前
鸿蒙Qt触控疑云:事件传递丢失与坐标偏移修复
qt·华为·harmonyos
_OP_CHEN2 天前
从零开始的Qt开发指南:(五)Qt 常用控件之 QWidget(上):解锁 Qt 界面开发的核心基石
开发语言·c++·qt·前端开发·qwidget·gui开发·qt常用控件
happyjoey2172 天前
使用Qt自带的Maintenance Tool将Qt6.9升级为QT6.10
开发语言·qt