0.QCustomPlot介绍
QCustomPlot是一个基于Qt画图和数据可视化的C++控件。在Qt下的绘图工具有Qwt、QChart和QCustomPlot,置于选择哪个绘图工具各有优缺点。
在绘制大量数据(10万个点以上)时选择QCustomPlot,在数据量比较小时,QChart和QCustomPlot相差无几。
1.QCustomPlot的下载
QCustomPlot官网地址:https://www.qcustomplot.com/index.php/introduction
下载地址:https://www.qcustomplot.com/index.php/download
-
目前最新的是2.1.0,直接下载QCustomPlot.tar.gz、QCustomPlot-sharedlib.tar.gz两个文件并解压。
2.QCustomPlot的几个重要类
- QCustomPlot 图表类:用于图表的显示和交互;
- QCPLayer 图层:管理图层元素(QCPLayerable),所有可显示的对象都是继承自图层元素;
- QCPAbstractPlottable 绘图元素:包含 折线图(QCPGraph)、曲线图(QCPCurve)、柱状图(QCPBars)、QCPStatiBox(盒子图)、QCPColorMap(色谱图)、QCPFinancial(金融图);
- QCPAxisRect 坐标轴矩形:一个坐标轴矩形默认包含上下左右四个坐标轴,但是可以添加多个坐标轴;
3.QCustomPlot的使用源码
3.1使用源码
- Qt新建一个工程文件,QCustomPlot.tar.gz后将qcustomplot.h与qcustomplot.cpp拷贝到工程目录下,右键 -> 添加现有文件…,将这两个文件添加至工程。
- 在pro中添加(由于QCustomPlot中存在导出功能,使用了printsupport模块)
QT += printsupport
- 在使用qcustomplot的文件中添加包含头文件:
#include "qcustomplot.h"
-
在*.ui文件中,选择widget控件,右键将其提升为QCustomPlot,然后头文件哪里会自动填充为qcustomplot.h。
-
运行程序就可以看见控件效果了,由于直接使用
QCustomPlot
源码,所以编译运行速度会比较慢。
3.2使用QCustomPlot编译成动态库
- 解压
QCustomPlot-sharedlib.tar.gz
,将QCustomPlot.tar.gz
中的qcustomplot.cpp
和qcustomplot
文件复制到和QCustomPlot-sharedlib.tar.gz
解压的文件夹同级目录下,如下图:
- 用Qt打开项目,我的路纪
C:\QCustomPlot-sharedlib\qcustomplot-sharedlib\sharedlib-compilation\sharedlib-compilation.pro
- 选择
debug
或者Release
,进行构建。将会在debug
目录下生成libqcustomplotd2.a
、qcustomplotd2.dll
,在release
目录下生成libqcustomplot2.a
、qcustomplot2.dll
。接下来我们在使用的时候只需要我拷贝qcustomplot.h
和动态库就可以。
4.添加帮助文档
由于下载是第三方的C++控件库,没有帮助文档。需要我们人为的手动添加。
在下载的documentation文件夹下有个qcustomplot.qch文件,将其拷贝到Qt的文档路径(C:\Qt\Qt5.13.0\Docs),在QtCreator->工具->工具->选项->帮助->文档->添加,选择qcustomplot.qch文件,确定,这样以后我们F1就可以跳转到QCustomPlot的帮助文档了。
5.简单使用
- 新建一个项目在.ui界面文件中,拖拉一个widget控件,命名为
customPlot
,右键将其提升为QCustomPlot
,并命名为m_customPlot
,添加一个PushButtom
,命名为startBtn
。
- 在主程序添加代码:
// 生成数据,画出的是抛物线
QVector<double> x(101), y(101); //初始化向量x和y
for (int i=0; i<101; ++i)
{
x[i] = i/50.0 - 1; // x范围[-1,1]
y[i] = x[i]*x[i]; // y=x*x
}
ui->customPlot->addGraph();//添加数据曲线(一个图像可以有多个数据曲线)
// graph(0);可以获取某个数据曲线(按添加先后排序)
// setData();为数据曲线关联数据
ui->customPlot->graph(0)->setData(x, y);
ui->customPlot->graph(0)->setName("抛物线y=x²");// 设置图例名称
// 为坐标轴添加标签
ui->customPlot->xAxis->setLabel("x");
ui->customPlot->yAxis->setLabel("y");
// 设置坐标轴的范围,以看到所有数据
ui->customPlot->xAxis->setRange(-1, 1);
ui->customPlot->yAxis->setRange(0, 1);
ui->customPlot->legend->setVisible(true); // 显示图例
// 重画图像
ui->customPlot->replot();
- 运行结果