话不多说,QCustomPlot第二弹,实现动态折线图。
需要注意以下几点:
1、
//Qt中setData原型
void QCPGraph::setData(const QVector<double> &key, const QVector<double> &value)
QVector类是一个提供动态数组的模板类。QVector不能插入、添加、替换一个QVector,否则你的应用程序就会报错!
解决方法:定义临时变量。然后定义一个全局变量通过形参的方式,传入参数中。
2、
怎么样让折线图的数据变化,当然是通过产生随机数了,以下是Qt产生随机数的两种方法。
Qt中生成随机数
方式一:
#include <QTimer>
QTime t;
t= QTime::currentTime();
qsrand(t.msec()+t.second()*1000);
int n = qrand();
方式二:
#include <QTimer>
#include<time.h>
qsrand(time(NULL));
int n = qrand();
以下是源代码:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "qcustomplot.h"
#include <QVector>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
double tempnum[10];
int n;
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void SimpleDemo(QCustomPlot *customPlot,double tempnum[10],int i);
public slots:
void SimpleDemo();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVector>
#include <QTimer>
#include <QTime>
//#include <time.h>
//#include "qcustomplot.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
for(int i=0;i<10;i++)
{
tempnum[i] = 0;
}
n=0;
QTimer *timer = new QTimer(this);
timer->start(2000);
connect(timer,SIGNAL(timeout()),this,SLOT(SimpleDemo()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::SimpleDemo()
{
QTime t;
t=QTime::currentTime();
qsrand(t.msec()+t.second()*1000);
n=qrand()%50+5;
SimpleDemo(ui->qCustomPlot,tempnum,n);
}
void MainWindow::SimpleDemo(QCustomPlot *CustomPlot,double tempnum[10],int i)
{
QVector<double> temp(10);
QVector<double> temp1(10);
for(int i=8;i>=0;i--)
{
tempnum[i+1]=tempnum[i];
}
tempnum[0]=n;
for(int i=0;i<10;i++)
{
temp[i] = i;
temp1[i] =tempnum[i];
}
CustomPlot->addGraph();
CustomPlot->graph(0)->setPen(QPen(Qt::red));
CustomPlot->graph(0)->setData(temp,temp1);
CustomPlot->xAxis->setLabel("time");
CustomPlot->yAxis->setLabel("temp/shidu");
CustomPlot->xAxis->setRange(0,11);
CustomPlot->yAxis->setRange(0,100);
CustomPlot->replot();
}
main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
下面来看看效果吧。。。
原文链接:https://blog.csdn.net/scgaliguodong123_/article/details/40747861
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
还没有人抢沙发呢~