【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;
}
相关推荐
阑梦清川4 分钟前
AI超级智能体项目教程(二)---后端项目初始化(设计knif4j接口文档的使用)
java·前端·数据库
hotlinhao4 分钟前
ThinkPHP6模型中多组条件逻辑或Or查询的使用
linux·服务器·数据库
jack xu111 分钟前
高频面试题:如何保证数据库和es数据一致性
java·大数据·数据库·mysql·elasticsearch
Pocker_Spades_A15 分钟前
金仓数据库征文-政务领域国产化数据库更替:金仓 KingbaseES 应用实践
数据库·政务·金仓数据库 2025 征文·数据库平替用金仓
niuTaylor32 分钟前
Linux驱动开发快速上手指南:从理论到实战
linux·运维·开发语言·驱动开发·c#
XY.散人32 分钟前
初识Redis · 哨兵机制
数据库·redis·缓存
__淡墨青衫__1 小时前
Django之旅:第七节--模版继承
数据库·django·sqlite
军训猫猫头1 小时前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf
秃头佛爷1 小时前
常用SQL整理
数据库·sql
时序数据说1 小时前
时序数据库IoTDB与OpenTSDB的对比分析
大数据·数据库·时序数据库·iotdb·opentsdb