当前位置:网站首页>Qt | 定时器的使用 QTimer
Qt | 定时器的使用 QTimer
2022-08-02 14:12:00 【华为云】
在 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()));
函数原型有两个:
1.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);
参数一为时间间隔,单位毫秒;参数二为定时器的精确度(同上文);参数三为接收溢出信号的对象;参数四为溢出信号的槽函数。
另:
都可以用到的一些函数:
判断定时器是否正在运行:bool QTimer::isActive () const
改变定时器的时间间隔:void QTimer::changeInterval ( int msec )
如果这个定时器正在运行,他将被停止并且重新开始,否则将会被开始。
边栏推荐
猜你喜欢
随机推荐
二叉排序树与 set、map
KiCad Common Shortcuts
2021-03-12
3.用户上传头像
What are IPV4 and IPV6?
测试用例练习
队列与栈
Detailed introduction to the hierarchical method of binary tree creation
二叉树创建之层次法入门详解
快速排序
MMD->Unity一站式解决方案
数学工具-desmos 图形曲线
开源一个golang写的游戏服务器框架
Summarize computer network super comprehensive test questions
3. User upload avatar
Based on the least squares linear regression equation coefficient estimation
Article pygame drag the implementation of the method
C语言函数参数传递模式入门详解
shader入门精要3
unity 和C# 一些官方优化资料









