Qt定时器目前有两种:
1.QObiect类的定时器。
2.QTimer类定时器。
定时器的精确度依赖于操作系统和硬件,大多数平台支持20ms的精确度。
1.相关函数:
int startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer);
函数描述:
启动计时器并返回计时器标识符,如果无法启动计时器,则返回零。
计时器事件将每间隔毫秒发生一次,直到调用killTimer()。如果interval为0,那么每次没有更多的窗口系统事件要处理时,定时器事件就会发生一次。
发生定时器事件时,使用 QTimerEvent 事件参数类调用虚拟 timerEvent() 函数。 重新实现此函数以获取计时器事件。
如果多个定时器正在运行,QTimerEvent::timerId() 可以用来找出哪个定时器被激活。
参数:
int interval:时间间隔,单位毫秒。
Qt::TimerType timerType:计时器的精确度类型,默认为CoarseTimer。.
PreciseTimer:精确计时器试图保持毫秒精度
CoarseTimer:粗略计时器尝试将精度保持在所需间隔的 5% 内
VeryCoarseTimer:非常粗略的计时器
void killTimer(int id);
函数描述:使用计时器标识符(id)终止计时器。
virtual void timerEvent(QTimerEvent *event);
函数描述:此事件处理程序可以在子类中重新实现,以接收对象的计时器事件。
QTimerEvent *event: event.timerId() 获取
定时器类QTimer提供当定时器触发的时候发射一个信号的定时器,它提供只触发一次的超时事件.
QTimer *testTimer = newQTimer ( this );
connect ( testTimer, SIGNAL (timeout()), this, SLOT (timeoutFun()));
testTimer->start ( 1000 );
if( testTimer->isActive() )
{
testTimer->stop();
}
单次计时器只触发一次,非单次计时器每间隔毫秒触发一次,此属性的默认值为 false(即非单次计时器)。
testTimer->setSingleShot(true);//可以改变此属性,设置为true时只出发一次timeout事件。
testTimer->isSingleShot();
Qt::TimerType timerType();
void setTimerType(Qt::TimerType atype);
一般地,默认属性为Qt::PreciseTimer
Qt::PreciseTimer 0 Precise timers try to keep millisecond accuracy(精确计时器试图保持毫秒精度)
Qt::CoarseTimer 1 Coarse timers try to keep accuracy within 5% of the desired interval(粗略计时器尝试将精度保持在所需间隔的 5% 内)
Qt::VeryCoarseTimer 2 Very coarse timers only keep full second accuracy(非常粗略的计时器只能保持整秒精度)
int remainingTime();
此属性以毫秒为单位保存剩余时间返回定时器的剩余值,以毫秒为单位,直到超时。 如果计时器处于非活动状态,则返回值为 -1。如果定时器超时,返回值为0。
void setInterval(int msec);
int interval() const { return inter; }
int timerId()
QTimer::singleShot(100, this, SLOT( animateTimeout()));
QTimer::singleShot(50, this, [=] {m_thread->start();});