【QT】C#中System.Timers.Timer定时触发事件的计时器类,qt与之对应的QTimer类的使用举例

一个桌面应用程序,该应用程序需要定期更新一些数据,以确保用户始终看到最新的信息。

.h

cpp 复制代码
#ifndef TIMEREXAMPLE_H
#define TIMEREXAMPLE_H

#include <QObject>
#include <QTimer>
#include <QDateTime>

class TimerExample : public QObject
{
    Q_OBJECT

public:
    explicit TimerExample(QObject *parent = nullptr);
    ~TimerExample();

signals:
    void dataUpdated(QString newData);

public slots:
    void updateData();

private:
    QTimer *timer;
    QString currentData;
};

#endif // TIMEREXAMPLE_H

cpp

cpp 复制代码
#include "timerexample.h"
#include <QDebug>

TimerExample::TimerExample(QObject *parent) : QObject(parent)
{
    // 创建定时器对象
    timer = new QTimer(this);

    // 连接定时器的timeout()信号到槽函数
    connect(timer, SIGNAL(timeout()), this, SLOT(updateData()));

    // 设置定时器的时间间隔,单位是毫秒
    timer->start(5000); // 每隔5秒触发一次timeout()信号

    // 初始化数据
    currentData = "Initial data";
}

TimerExample::~TimerExample()
{
    // 在对象销毁时,停止定时器并释放资源
    timer->stop();
    delete timer;
}

void TimerExample::updateData()
{
    // 模拟从服务器或其他来源获取新数据的操作
    QDateTime currentTime = QDateTime::currentDateTime();
    currentData = "Updated data at " + currentTime.toString("hh:mm:ss");

    // 发送信号,通知数据已经更新
    emit dataUpdated(currentData);
    qDebug() << "Data updated:" << currentData;
}
相关推荐
库库林_沙琪马26 分钟前
Redis 持久化:从零到掌握
数据库·redis·缓存
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
牵牛老人2 小时前
Qt中使用QPdfWriter类结合QPainter类绘制并输出PDF文件
数据库·qt·pdf
水瓶丫头站住2 小时前
Qt的QStackedWidget样式设置
开发语言·qt
卡西里弗斯奥4 小时前
【达梦数据库】dblink连接[SqlServer/Mysql]报错处理
数据库·mysql·sqlserver·达梦
温柔小胖4 小时前
sql注入之python脚本进行时间盲注和布尔盲注
数据库·sql·网络安全
慕诗客5 小时前
QT基于Gstreamer采集的简单示例
开发语言·qt
Blasit5 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http
黄金小码农5 小时前
c# 2025/2/19 周三
c#