自定义定时器类
.h文件
#ifndef PERFORMANCETIMER_H
#define PERFORMANCETIMER_H
#include <QObject>
#include <windows.h>
class PerformanceTimer : public QObject
{
Q_OBJECT
public:
explicit PerformanceTimer(QObject *parent = 0);
~PerformanceTimer();
signals:
void timeout();
public slots:
void start(int timeInterval);
void stop();
friend WINAPI void CALLBACK PeriodCycle(uint,uint,DWORD_PTR,DWORD_PTR,DWORD_PTR);
private:
int m_interval;
int m_id;
};
#endif // PERFORMANCETIMER_H
.cpp文件
#include "performancetimer.h"
#ifdef __MINGW32__
#define TIME_KILL_SYNCHRONOUS 0x0100
#endif
void CALLBACK PeriodCycle(uint timerId,uint,DWORD_PTR user,DWORD_PTR,DWORD_PTR)
{
PerformanceTimer *t=reinterpret_cast<PerformanceTimer *>(user);
emit t->timeout();
}
PerformanceTimer::PerformanceTimer(QObject *parent) : QObject(parent)
{
m_id=0;
}
PerformanceTimer::~PerformanceTimer()
{
stop();
}
void PerformanceTimer::start(int timeInterval)
{
m_id=timeSetEvent(timeInterval,1,PeriodCycle,(DWORD_PTR)this,
TIME_CALLBACK_FUNCTION|TIME_PERIODIC|TIME_KILL_SYNCHRONOUS);
}void PerformanceTimer::stop()
{
if(m_id)
{
timeKillEvent(m_id);
m_id=0;
}
}
使用方法是按照以上代码完成该自定义类,然后在其他需要定时器的地方写入代码,声明一个定时器对象,然后使用该定时器的信号timeout()绑定需要的槽函数,然后根据不同的条件开始或者结束该时钟,具体代码如下:
PerformanceTimer *timer=new PerformanceTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(slotFuction()));
timer->start(20); //20为毫秒
或者timer->stop();