以下是一个简单的示例程序,使用QT的QCustomPlot库绘制实时二维动态曲线:

#include <QApplication>
#include <QMainWindow>
#include <QTimer>
#include "qcustomplot.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QMainWindow window;
    window.setWindowTitle("Real-time Plot");
    window.resize(800, 600);

    QCustomPlot plot(&window);
    plot.setGeometry(50, 50, 700, 500);

    plot.addGraph(); // 添加一个曲线
    plot.graph(0)->setPen(QPen(Qt::blue)); // 设置曲线的颜色

    plot.xAxis->setLabel("Time (s)"); // 设置x轴的标签
    plot.yAxis->setLabel("Value"); // 设置y轴的标签

    plot.xAxis->setRange(0, 10); // 设置x轴的范围
    plot.yAxis->setRange(0, 100); // 设置y轴的范围

    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, [&]() {
        static double t = 0;
        double y = 50 + 50 * qSin(t); // 计算y值,这里假设y是一个随时间变化的正弦函数
        plot.graph(0)->addData(t, y); // 添加数据点
        plot.graph(0)->removeDataBefore(t - 10); // 移除10秒前的数据点
        plot.replot(); // 重新绘制曲线
        t += 0.1; // 增加时间
    });
    timer.start(100); // 每隔100毫秒更新一次曲线

    window.show();

    return a.exec();
}

这个程序中,我们创建了一个QMainWindow窗口,上面放置了一个QCustomPlot控件,用于绘制实时二维动态曲线。在QCustomPlot中,我们添加了一个曲线,并设置了它的颜色、标签、范围等属性。然后,我们使用QTimer定时器每隔一段时间更新曲线的数据,计算y值并添加到曲线上,同时移除10秒前的数据点,最后重新绘制曲线。这样,就可以实现实时的二维动态曲线了


原文地址: https://www.cveoy.top/t/topic/c1pq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录