头文件
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_Qt8_2A.h"
class Qt8_2A : public QMainWindow
{
Q_OBJECT
public:
Qt8_2A(QWidget *parent = Q_NULLPTR);
virtual void timerEvent(QTimerEvent *event);
private:
Ui::Qt8_2AClass ui;
int m_timerId;
};
CPP文件
#include "Qt8_2A.h"
#include<QTime> // 要用到currentTime 函数
#include<QDebug> // 在调试界面中显示想要显示的内容
Qt8_2A::Qt8_2A(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
// 启动定时器,同时设定时间间隔
m_timerId = startTimer(1000);
}
// 首先要在头问件中声明一个定时的虚函数 virtual void timerEvent(QTimerEvent *event);
// 然后在cpp中重写该函数
// 在头文件中声明int变量m_timerId
// 利用startTimer(1000)函数启动定时器
//
void Qt8_2A::timerEvent(QTimerEvent * event)
{
if (event->timerId() == m_timerId)
{
QTime now = QTime::currentTime();
QString text = now.toString("HH:mm:ss");
qDebug() << text;
ui.label_timer->setText(text);
}
}
运行后的结果
本文介绍了一个使用Qt框架实现的简单定时器应用案例。通过启动一个每秒更新的定时器,展示如何在GUI中显示当前时间,并利用Qt的内置类QTime获取系统时间。
754

被折叠的 条评论
为什么被折叠?



