一:绘图样式初始化函数PlotInit() 1、关于字体设置
QFont font; font.setStyleStrategy(QFont::NoAntialias);//设置字体样式 customPlot->xAxis->setTickLabelFont(font);//x轴字体设置 customPlot->yAxis->setTickLabelFont(font);//y轴字体设置 customPlot->legend->setFont(font);//图例字体设置2、新建图层并设置图层曲线颜色 添加曲线一:
customPlot->addGraph(); //新建图层 customPlot->graph(0)->setPen(QPen(Qt::blue));//颜色设置:蓝色 customPlot->graph(0)->setName("曲线1");//图例名称添加曲线二:
customPlot->addGraph(); customPlot->graph(1)->setPen(QPen(Qt::red));颜色设置:蓝色 customPlot->graph(1)->setName("曲线二");3、设置x坐标轴
customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);//x轴坐标设定为时间 customPlot->xAxis->setDateTimeFormat("hh:mm:ss");//设定x坐标的时间格式 customPlot->xAxis->setAutoTickStep(false);//关闭自动轴间隔 customPlot->xAxis->setTickStep(2);//设置轴间隔为2s customPlot->axisRect()->setupFullAxesBox();//显示方框 customPlot->legend->setVisible(true);//显示图例二、初始化完成后,将定时器与作图槽函数realTimePlot()连接,每次定时时间到则刷新作图。即添加下面这段代码到自定义的绘图初始化函数PlotInit()末尾
connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));//连接定时器和作图函数,定时时间到则作一次图 dataTimer.start(0); // 定时周期0s,尽快刷新作图三、绘图函数realTimePlot()
void MainWindow::realtimeDataSlot() { double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;//横坐标数据为时间 qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);//随机数种子 double value0 = qrand() % 10;//产生随机数测试 double value1 = qrand() % 5; customPlot->graph(0)->addData(key, value0);//添加数据1到曲线1 customPlot->graph(1)->addData(key, value1);//添加数据2到曲线2 connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));//x轴范围变化时启动槽函数setRange,以实现x轴左移 customPlot->graph(0)->rescaleValueAxis(true);//y轴的范围自动调整,避免数据超出y轴 customPlot->graph(1)->rescaleValueAxis(true); customPlot->xAxis->setRange(key, 8, Qt::AlignRight);//设定x轴的范围为key到key+8,方式为右对齐 customPlot->replot();//重绘 }-----------------------------------工程文件配置------------------------------------
MainWindow.h ** MainWindow.cpp UI界面 运行结果