我是看了http://blog.csdn.net/coekjin/article/details/52123877的文章,写的很详细,只是代码缺少注释,我这里给些注释,希望对大家有所帮助。
#include "widget.h"
#include "ui_widget.h"
#include <QVector>
#include <QTime>
#include <QTimer>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//头文件中声明了num[]和n,这里给出初始化
for(int i=0;i<10;i++)
{
num[i] = 0;
}
n=0;
//定义定时器,500ms触发一次
QTimer *timer = new QTimer(this);
timer->start(500);
//信号与槽关联,定时器触发时响应Graph_Show()函数
connect(timer,SIGNAL(timeout()),this,SLOT(Graph_Show()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::Graph_Show()
{
//取随机数,返回0-50之间的值
QTime t;
t=QTime::currentTime();
qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
n=qrand()%50;
//调用Graph_Show(QCustomPlot)函数
Graph_Show(ui->widget);
}
//画图
void Widget::Graph_Show(QCustomPlot *CustomPlot)
{
//分别存储x坐标和y坐标
QVector<double> temp(10);
QVector<double> temp1(10);
for(int i=0; i<9; i++)
{
num[i]=num[i+1];
}
num[9]=n;
//初始化temp[]={0,1,2,3,4,5,6,7,8,9},temp1[]={0,0,0,0,0,0,0,0,0,0}
for(int i=0;i<10;i++)
{
temp[i] = i;
temp1[i] =num[i];
}
//添加一条曲线
CustomPlot->addGraph();
//x是曲线序号,添加的第一条是0,设置曲线颜色
CustomPlot->graph(0)->setPen(QPen(Qt::red));
//输出各点的图像,x和y都是QVector类
CustomPlot->graph(0)->setData(temp,temp1);
//x轴的文字
CustomPlot->xAxis->setLabel("t");
//y轴的文字
CustomPlot->yAxis->setLabel("mV");
//x轴范围
CustomPlot->xAxis->setRange(0,10);
//y轴范围
CustomPlot->yAxis->setRange(-50,50);
//重绘,这个是实时绘图的关键
CustomPlot->replot();
}
原博主已经讲解的很清楚了,只是代码和解释没放在一起。
附上一张效果图: