自学内容网 自学内容网

qtimer动态更新GUI数据

前言

QTimer

  • QTimer 是一个事件驱动的定时器,它在 Qt 的事件循环中触发。
  • 它适用于需要周期性更新 UI 的场景,例如实时监控、动画等。
  • QTimer 可以在主线程中使用,也可以安全地用于跨线程更新 UI,因为它的 timeout() 信号可以在主线程中处理。
  • 使用 QTimer 时,你不需要担心线程安全问题,因为所有的更新都会通过 Qt 的事件系统进行。
  • QTimer 不会创建新的线程,因此它不会增加额外的资源消耗。

一、 创建QTimer

        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &MyWidget::updateData);
        timer->start(1000); // 每隔1000毫秒更新一次

 二、连接信号跟槽


private slots:
    void updateData() {
        // 获取新数据
        static int count = 0;
        QString newData = QString("Updated Data %1").arg(++count);
        // 更新 QLabel
        uiLabel->setText(newData);
    }

三、更新GUI 

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MyWidget widget;
    widget.show();
    return app.exec();
}

四、测试代码示例 

#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QVBoxLayout>
#include <QTimer>

class MyWidget : public QWidget {
    Q_OBJECT
public:
    MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
        QVBoxLayout *layout = new QVBoxLayout(this);
        auto *label = new QLabel("Initial Data", this);
        layout->addWidget(label);
        uiLabel = label;

        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &MyWidget::updateData);
        timer->start(1000); // 每隔1000毫秒更新一次
    }

private slots:
    void updateData() {
        // 获取新数据
        static int count = 0;
        QString newData = QString("Updated Data %1").arg(++count);
        // 更新 QLabel
        uiLabel->setText(newData);
    }

private:
    QLabel *uiLabel;
};

#include "main.moc"

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MyWidget widget;
    widget.show();
    return app.exec();
}

 

 

 


原文地址:https://blog.csdn.net/canyuemanyue/article/details/142695194

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!