目录
- 1.前言
- 2.代码示例
- 3.运行结果
- 4.解释说明
经过上一节的基础介绍,相信对QCustomPlot有了基本了解,本文将介绍QCustomPlot的另外一个实例——在Qt上绘制多条曲线。
1.前言基础部分就不过多介绍了,不懂得可以直接参考:QCustomPlot基础教程(一)——QCustomPlot的安装及基础实例,直接上代码。
2.代码示例以官网代码为例,绘制两条曲线代码如下:
QCustomPlot *customPlot = ui->customPlot;//创建customPlot
//每条曲线都会独占一个graph()
customPlot->addGraph();
customPlot->graph(0)->setPen(QPen(Qt::blue)); // 曲线的颜色
customPlot->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20))); // 曲线与X轴包围区的颜色
customPlot->addGraph();//添加graph等价于添加一条新曲线
customPlot->graph(1)->setPen(QPen(Qt::red)); // 曲线的颜色
// 生成模拟数据点 (x-y0 第一条曲线, x-y1为第2条曲线):
QVector x(251), y0(251), y1(251);
for (int i=0; ixAxis2->setVisible(true);
customPlot->xAxis2->setTickLabels(false);
customPlot->yAxis2->setVisible(true);
customPlot->yAxis2->setTickLabels(false);
// 使上下两个X轴的范围总是相等,使左右两个Y轴的范围总是相等
connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
// 把已存在的数据填充进graph的数据区
customPlot->graph(0)->setData(x, y0);
customPlot->graph(1)->setData(x, y1);
//自动调整XY轴的范围,以便显示出graph(0)中所有的点(下面会单独讲到这个函数)
customPlot->graph(0)->rescaleAxes();
//自动调整XY轴的范围,以便显示出graph(1)中所有的点
customPlot->graph(1)->rescaleAxes(true);
// 支持鼠标拖拽轴的范围、滚动缩放轴的范围,左键点选图层(每条曲线独占一个图层)
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
// 立即刷新图像
ui->customPlot->replot();
3.运行结果
- 每一条曲线都必须独占一个graph,新建graph可通过addGraph()来实现。
- 每一个QCustomPlot都有上下左右4个坐标轴,分别为customPlot->xAxis2、xAxis、yAxis、yAxis2。 每个轴可设置是否显示、是否显示刻度、几个刻度、刻度的值是否显示等。
- 如果想将多条曲线的x轴和y轴范围全部显示出来,需要用到“自动缩放轴的范围”函数: rescaleAxes( bool onlyEnlarge = false) 该函数的作用是,使当前plot的XY的显示范围恰好(不能大也不能小)容纳本曲线,如果plot中有多条曲线,我们依次执行:
customPlot->graph(0)->rescaleAxes();
customPlot->graph(1)->rescaleAxes(true);
customPlot->graph(2)->rescaleAxes(true);
...//全都是true
完整代码也可以参考:https://download.csdn.net/download/didi_ya/21985010
以上便是本文的全部内容了,下一篇文章将介绍一下如何在Qt上绘制柱状图,如果对你有所帮助,记得点个赞哟~