Qt:QTimer

1、说明

QTimer类代表计时器,为了正确使用计时器,可以构造一个QTimer,将它的timeout()信号connect到合适的,之后调用start()。然后,这个QTimer就会每隔interval就发送一个timeout()信号。

一个间隔为1s(1000ms)的计时器

QTimer * timer = new QTimer(this);
connect(timer , &QTimer::timeout , this , QOverload<>::of(&AnalogClock::update));
timer->start(1000);

本例中,在start()计时器之后,update()槽函数将被每秒调用一次。

如果想要只超时一次,可以调用方法setSingleShot( true )。我们可以通过调用静态方法QTimer::singleShot()来在指定interval之后调用某个槽函数:

QTimer::singleShot(200,this,&Foo::updateCaption);

在多线程应用中,我们可以在每个使用事件循环(event looop)的线程中使用QTimer。使用QThread::exec()方法,可以从非GUI线程start event loop。Qt使用计时器的 thread affinity(线程事务)去决定发送哪个timeout()信号。因此,只需要在一个线程中startstop计时器就可以了。

 

2、模块和加载项

Header #include<QTimer>
qmake QT += core
Inherits QObject

3、属性

类型

属性

说明

getter与setter

信号

bool active 当计时器运行时,这个属性是true,否则是false  isActive()  
int interval 计时器间隔(毫秒)

 interval()

setInterval(int msec)

setInterval(std::chrono::milliseconds value)

 
int remainingTime 到计时器停止的剩余时间(毫秒) remainingTime()  
bool singleShot 该计时器是否是单响计时器

isSingleShot()

setSingleShot(bool singleShot)

 
TimerType timerType 控制计时器的精度

timerType()

setTimerType(Qt::TimerType atype)

 

4、构造

QTimer(QObject *parent = nullptr)

在给定的parent上构造计时器

5、成员方法

返回值类型

方法

说明

QMetaObject::Connection callOnTimeout(Functor slot, Qt::ConnectionType connectionType = Qt::AutoConnection)  建立信号与槽之间的连接,等价于调用QObject::connect(timer , timeout() , receiver , slot , connectionType)
 callOnTimeout(const QObject *context, Functor slot, Qt::ConnectionType connectionType = Qt::AutoConnection)
callOnTimeout(const QObject *receiver, MemberFunction *slot, Qt::ConnectionType connectionType = Qt::AutoConnection 
 int interval()   

std::chrono::milliseconds

intervalAsDuration()   返回interval对应的std::chrono::milliseconds对象
 bool isActive()  当计时器运行时返回true,否则false
 bool remainingTime()   
std::chrono::milliseconds  remainingTimeAsDuration()   返回remaining time对应的std::chrono::milliseconds对象
 void     setInterval(int msec)  
setInterval(std::chrono::milliseconds value  
 setSingleShot(bool singleShot)  
setTimerType(Qt::TimerType atype  
 void start(int msec 重启一个interval为msec的计时器
 int timerId()  返回计时器的ID
 Qt::TimerType timerType()   

5.5、静态方法

void singleShot( ... )  设置一个单响计时器

 

6、槽

槽函数

说明

start() 启动计时器(如果已经启动则重启)
start(int msec) 重启一个间隔为msec的计时器 
stop() 停止计时器 

7、信号

timeout() 超时是发送该消息
posted @   ShineLe  阅读(726)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示