qt的QCustomPlot绘制实时曲线图总结

一、组件的下载

下载下来后文件如下图所示,具有丰富的例程,这个很好,注意后面要用到的c++文件和头文件,听说还有丰富的帮助文档,暂时没有时间去找,大概翻看了一下没有看到

二、拷贝.h 和c++文件到工程目录,如下图;并添加到工程目录中

三、在ui窗口中增加一个QCustomPlot绘图对象,可以用对象提升的办法

四、修改主窗口的头文件,主要增加了起始时间,一个定时器和一个绘图的槽函数

cpp 复制代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "QCustomPlot.h"
#include <QDateTime>
#include <QMainWindow>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private slots:
    void updateGraph();
private:
    QTimer *updateTimer;
    QTime  startTime;
private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

五、修改构造函数及绘图槽函数如下图所示

cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QObject>
#include <QVector>
#include <QTime>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->widget_xy->addGraph();
    ui-> widget_xy->graph(0)->setPen(QPen(Qt::blue));
    ui->widget_xy->xAxis->setLabel("Time (s)");
    ui->widget_xy->yAxis->setLabel("Value");
    ui-> widget_xy->xAxis->setRange(0, 5);
    ui->widget_xy->yAxis->setRange(0, 100); // 假设纵坐标范围为 0 - 100,可以根据实际情况调
    startTime = QTime::currentTime();
    updateTimer = new QTimer(this);
    updateTimer->setInterval(10); // 每 100 毫秒更新一次
    connect(updateTimer, &QTimer::timeout, this, &MainWindow::updateGraph);
    updateTimer->start();

}
MainWindow::~MainWindow()
{
    delete ui;
    // delete updateTimer;
}
void MainWindow::updateGraph()
{
    double currentTime = startTime.msecsTo(QTime::currentTime()) / 1000.0;
    // double value = startTime.msecsTo(QTime::currentTime()) % 100; // 生成随机值作为示例,可以替换为实际值
    double value=ui->verticalSlider->value();
    QVector<double> x, y;
    x.append(currentTime);
    y.append(value);

    ui->widget_xy->graph(0)->addData(currentTime, value);
    // ui->widget_xy->graph(0)->setData(x, y);

    if (currentTime > 5)
    {
        ui->widget_xy->xAxis->setRange(currentTime - 5, currentTime);
    }
    ui->widget_xy->replot();
}

五、运行结果如下图

总结:1、改绘图是根据鼠标的拖动值来绘制曲线的;

2、注意下面这两行代码的区别,addData是在原有曲线上增加一个点,而setData是整体替换;

上述代码是在ai助手编写的,就是有这样的错误,花了不少时间查找代码的原因;

3、这个代码需要改进的地方,因为定义的向量 x,y几乎都没有数据,一直为一个元素,也就是没有发挥出向量的作用,同时,无法为曲线的存储和回放提供基础数据。

cpp 复制代码
 ui->widget_xy->graph(0)->addData(currentTime, value);
    // ui->widget_xy->graph(0)->setData(x, y);

时间关系,基于qt的QCustomPlot的先告一段落,记录一下,转入c#

相关推荐
丰锋ff5 小时前
3.1 Qt事件之事件处理器
开发语言·qt
反转180度7 小时前
Qt 6 + C++17 实现 SFTP 批量部署:工业设备运维工具实战解析
运维·c++·qt
我不是疯子是傻子9 小时前
Qt CAN通信周期发送抖动?实测定时器精度校准与时间戳补偿方案
开发语言·数据库·qt
2023自学中10 小时前
Qt 简易聊天室(第二篇),单线程 改为 多线程,方便后续增加文件传输功能
c++·qt
丰锋ff15 小时前
1.7在Qt窗口中添加右键菜单
开发语言·qt
richard_yuu19 小时前
JSON vs XML vs 二进制:3种序列化终极选型
xml·c++·qt·学习·json
秋田君20 小时前
QT_实战TCP 聊天程序说明文档以及实现
数据库·qt·tcp/ip
byxdaz1 天前
QT中服务使用
开发语言·qt
秋田君2 天前
QT_网络编程体系
网络·arm开发·qt
Quz2 天前
QML TextArea 实战(下):大文本加载与性能优化
qt