Qt5_QCustomPlot畫實時動態曲線(1)

在Qt中畫圖的方式有很多,之前我們提到過使用重構paintevent來畫實時動態圖。本週我們想通過對數據的統計,將統計到的實時數據通過曲線圖的方式表現出來。經過調研和查閱資料,我們發現使用QCustomPlot可以很好的完成需求。
QCustomPlot的安裝與運行在這裏不講,我們主要來關注如何繪製出實時動態曲線圖。
我們的想法是,使得數據向左移,然後將新的數據畫出,然後又得到一個新的值,再將數據左移,繼續畫出。具體代碼實現如下:

//curvewidget.h
#ifndef CURVEWIDGET_H
#define CURVEWIDGET_H

#include <QWidget>
#include"../../qcustomplot/qcustomplot.h"

class curvewidget : public QWidget
{
    Q_OBJECT
public:
    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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章