1.下载并添加qcustomplot.c和qcustomplot.h文件
拖动一个Widget,提升为qcustomplot
成功后是这样的,
改第三行:greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport 编译,不报错,出现带坐标轴的界面,成功
2.生成曲线
mainwindow.h增加定时器等等
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "qcustomplot.h" // 引入QCustomPlot头文件QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;QCustomPlot *customPlot; // 添加QCustomPlot指针QTimer *dataTimer; // 定时器QVector<double> xData, yData; // 数据存储void updatePlot(); // 更新图表的函数
};#endif // MAINWINDOW_H
main函数增加曲线等
#include "mainwindow.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);MainWindow w;w.show();return a.exec();
}
void MainWindow::updatePlot()
{// 生成新的数据点static double time = 0;static double signalValue = 0;// 生成新信号值(如正弦波)signalValue = qSin(time);time += 0.1;// 保存数据xData.append(time);yData.append(signalValue);// 更新图表customPlot->graph(0)->setData(xData, yData);customPlot->xAxis->setRange(time, 10, Qt::AlignRight); // X轴范围保持在最新10秒内customPlot->replot(); // 刷新图表
}
mianwindow.c添加曲线属性以及定时器参数等
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QVector>
#include <cmath> // 使用数学函数MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);// 初始化QCustomPlotcustomPlot = new QCustomPlot(this);setCentralWidget(customPlot);// 配置图表customPlot->addGraph();customPlot->graph(0)->setPen(QPen(Qt::blue)); // 设置曲线颜色customPlot->xAxis->setLabel("Time (s)");customPlot->yAxis->setLabel("Signal Value");// 启用自动缩放customPlot->xAxis->setRange(0, 10);customPlot->yAxis->setRange(-1, 1);// 初始化定时器dataTimer = new QTimer(this);connect(dataTimer, &QTimer::timeout, this, &MainWindow::updatePlot);dataTimer->start(100); // 每100毫秒更新一次// 初始化数据xData.clear();yData.clear();
}
MainWindow::~MainWindow()
{delete ui;
}
效果:动态正选曲线