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#

相关推荐
用户805533698035 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner5 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz10 天前
QML Hello World 入门示例
qt
xcyxiner13 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner14 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner14 天前
DicomViewer (添加模型类)3
qt
xcyxiner15 天前
DicomViewer (目录调整) 2
qt
xcyxiner15 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能17 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G17 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt