Qt5_QCustomPlot画实时动态曲线(1)

来源:互联网 发布:淘宝墙上挂的饰品 编辑:程序博客网 时间:2024/06/06 13:07

在Qt中画图的方式有很多,之前我们提到过使用重构paintevent来画实时动态图。本周我们想通过对数据的统计,将统计到的实时数据通过曲线图的方式表现出来。经过调研和查阅资料,我们发现使用QCustomPlot可以很好的完成需求。
QCustomPlot的安装与运行在这里不讲,我们主要来关注如何绘制出实时动态曲线图。
我们的想法是,使得数据向左移,然后将新的数据画出,然后又得到一个新的值,再将数据左移,继续画出。具体代码实现如下:

//curvewidget.h#ifndef CURVEWIDGET_H#define CURVEWIDGET_H#include <QWidget>#include"../../qcustomplot/qcustomplot.h"class curvewidget : public QWidget{    Q_OBJECTpublic:    explicit curvewidget(QWidget *parent = 0);    //void setupRealtimeDataDemo(QCustomPlot *customPlot);    void setupDataDemo(QCustomPlot *customPlot);    QCustomPlot *customPlot;    double tempnum[10];    double n;    void SimpleDemo(QCustomPlot *customPlot,double tempnum[10],double n);signals:public slots:   // void realtimeDataSlot();    //void showupdate();    void SimpleDemo();private:    QTimer dataTimer;};#endif // CURVEWIDGET_H
//curvewidget.cc#include "curvewidget.h"#include <QHBoxLayout>curvewidget::curvewidget(QWidget *parent) : QWidget(parent){    customPlot = new QCustomPlot(this);   // setupRealtimeDataDemo(customPlot);    //setupDataDemo(customPlot);    customPlot->setFixedSize(470,350);    for(int i=0; i<10; i++){        tempnum[i] = 0;    }    n=0;    QTimer *dataTimer= new QTimer();    //connect(dataTimer,SIGNAL(timeout()),this,SLOT(showupdate()));    connect(dataTimer,SIGNAL(timeout()),this,SLOT(SimpleDemo()));    dataTimer->start(1000);}void curvewidget::SimpleDemo(){    qsrand(time(NULL));    double n1;    double n2[50];    double sum=0;    for(int i = 0; i < 50; i++)        {            n1 = qrand()/100000000.0;            n2[i] = n1;    }    for(int i =0; i<50; i++)        {        sum +=n2[i];    }    n=sum;    SimpleDemo(customPlot,tempnum,n);}void curvewidget::SimpleDemo(QCustomPlot *customPlot,double tempnum[10],double n){    QVector <double> temp(10);    QVector <double> temp1(10);    for(int i=0; i<9; i++){        tempnum[i] =tempnum[i+1];    }    tempnum[9] = n;    for(int i = 0; i<10; i++)        {        temp[i] = i/10.0;        temp1[i] = tempnum[i];    }    customPlot->addGraph();    customPlot->graph(0)->setPen(QPen(QColor(70,0,70)));    customPlot->graph(0)->setData(temp,temp1);    customPlot->xAxis->setLabel("time");    customPlot->yAxis->setLabel("throughput/Mbps");    customPlot->xAxis->setRange(0,1);    customPlot->xAxis->setSubTickLength(0.1);    customPlot->yAxis->setRange(0,1000);    customPlot->replot();}

效果图如下:
效果图1
效果图2

0 0
原创粉丝点击