目录
Qt 使用只需要执行一次的定时器时最简单的方式
定时器的使用
一、直接使用QObject类
二、使用QTimer类。
三、仅调用一次溢出的定时器
============================
Qt 使用只需要执行一次的定时器时最简单的方式
一、前言
经常遇到使用一次定时器的情况,如何只是呆板的使用 定义,连接信号槽,定义槽函数,开启定时器,stop定时器,将会浪费很多时间精力。
二、正文
直接上代码
#include <QDebug>
#include <QTimer>
QTimer::singleShot(1000, this, [=](){
qDebug()<<"qtimer timeout after 1s";
});
三、结尾语
代码虽短,五脏俱全,使用到的知识点有
单次定时器
lambda匿名函数
————————————————
版权声明:本文为CSDN博主「Jeady5」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/downanddusk/article/details/120548602
==========================
Qt | 定时器的使用
在Qt中使用定时器一般有三种方式:
一、直接使用QObject类提供的定时器。
1.在需要开启定时器的地方直接调用
startTimer();
该函数的声明为:
int startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer);
该函数开启一个定时器,返回值是定时器的编号。
参数一为时间间隔,单位毫秒;
参数二为定时器的精确度:
Qt::PreciseTimer(精确的定时器,尽量保持毫秒精度,试图保持精确度在1毫秒);
Qt::CoarseTimer(粗略的定时器,尽量保持精度在所需的时间间隔5%范围内);
Qt::VeryCoarseTimer(很粗略的定时器,只保留完整的第二精度,大约为500毫秒);
2.重载
void QObject::timerEvent ( QTimerEvent * event );
当定时器溢出时,会自动响应timerEvent()函数。
在timerEvent()函数中,通过event->timerId()来确定是哪个定时器触发的;
3.在需要关闭定时器的地方调用
killTimer();
该函数的声明为: void killTimer(int Id);
该函数关闭一个定时器,参数为定时器的编号。
二、使用QTimer类。
1.用new的方式创建一个QTimer对象。
QTimer *timer = new QTimer(this);
2.将定时器的溢出信号连接到自定义的槽函数。
connect(timer, &QTimer::timeout, this, &Myself::update);
3.启动定时器。
timer->start(1000);
函数原型为:void start(int msec);参数为定时器时间间隔,单位毫秒。
也可以调用timer->setInterval(1000);设置定时器时间间隔,然后调用timer->start();开启定时器。
4.停止定时器。
timer->stop();
三、仅调用一次溢出的定时器。
QTimer::singleShot(1000, this, SLOT(OnSendBreath()));
函数原型有两个:
static void singleShot(int msec, const QObject *receiver, const char *member);
static void singleShot(int msec, const QObject *receiver, const char *member);
参数一为时间间隔,单位毫秒;
参数二为接收溢出信号的对象;
参数三为溢出信号的槽函数;
2. static void singleShot(int msec, Qt::TimerType timerType, const QObject *receiver, const char *member);
static void singleShot(int msec, Qt::TimerType timerType, const QObject *receiver, const char *member);
参数一为时间间隔,单位毫秒;
参数二为定时器的精确度(同上文);
参数三为接收溢出信号的对象;
参数四为溢出信号的槽函数。
另:
都可以用到的一些函数:
1. 判断定时器是否正在运行:
bool QTimer::isActive () const
2. 改变定时器的时间间隔:
void QTimer::changeInterval ( int msec )
如果这个定时器正在运行,他将被停止并且重新开始,否则将会被开始。
发布于 2022-01-20 15:55
转载:https://zhuanlan.zhihu.com/p/459900932
enum Qt::TimerType
Qt::PreciseTimer
Qt::CoarseTimer
Qt::VeryCoarseTimer
![](https://img-blog.csdnimg.cn/img_convert/ad69cc22250196452eed44f1aaafe0de.png)