可以在dialog上添加三个label查看时间和异常次数,也可以在打印输出栏看每次timer超时事件误差适度少(都是ms级别的)
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QDateTime>
namespace Ui {
class Dialog;
}
class QTimer;
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
public slots:
void slotOneSec();
private:
Ui::Dialog *ui;
QDateTime m_time;
QTimer *m_oneSecTimer;
int num;
};
#endif // DIALOG_H
#include "dialog.h"
#include "ui_dialog.h"
#include <QTimer>
#include <QDebug>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
num = 0;
m_oneSecTimer = new QTimer();
connect(m_oneSecTimer, SIGNAL(timeout()), this, SLOT(slotOneSec()));
m_time = QDateTime::currentDateTime();
m_oneSecTimer->start(1000);
ui->myTime->setText(m_time.toString("hh:mm:ss"));
ui->computerTime->setText(QDateTime::currentDateTime().toString("hh:mm:ss"));
}
Dialog::~Dialog()
{
delete m_oneSecTimer;
delete ui;
}
void Dialog::slotOneSec()
{
m_time = m_time.addSecs(1);
ui->myTime->setText(m_time.toString("hh:mm:ss"));
ui->computerTime->setText(QDateTime::currentDateTime().toString("hh:mm:ss"));
//如果两次定时间隔大于10秒,次数就会+1
qDebug()<<"===="<<abs(m_time.toMSecsSinceEpoch() - QDateTime::currentDateTime().toMSecsSinceEpoch());
if(abs(m_time.toMSecsSinceEpoch() - QDateTime::currentDateTime().toMSecsSinceEpoch()) > 10000)
{
num++;
}
ui->exception->setText(QString::number(num));
//校准事件
m_time = QDateTime::currentDateTime();
}
效果图