QCustomPlot简单应用

应用背景

对于一些测量系统,有时直接看数据并不是很直观,若将数据转换成图像来显示,会更直观,同时也能根据图像或曲线引出新的规律。
将数据换成图像显示时,有些也能验证的整个系统的测量是否正确。接下来介绍一种易用基于QT的曲线控件QCustomPlot。

介绍

QCustomPlot是一个用绘图与数据可视化的QT C++部件,没有基于其他依赖,同时有良好的文档说明。这个库可用于好看的,可出版的2D绘图,图形,图表。
并对于实时曲线绘制也有很高的性能。QCustomPlot可以导出多种格式,PDF,PNG,JPG,BMP等。QCustomPlot也是开源的基于GPL协议。用户可自由查看其源码。
可去其官网QCustomPlot查看详细说明。

Demo

Windows操作环境

  1. 先从官网下载代码,选择其中一个版本即可
  2. 将下载的源文件复制到工程目录,并将添加至工程,工程添加printsupport选项
    如下图所示
    demo project set
  3. 添加一个widget控件并promote to(提升至)QCustomPlot

  4. 直接使用widget的名字进行QCustomPlot API的调用来实现想要的结果


Sample Demo

// add two new graphs and set their look:
customPlot->addGraph();
customPlot->graph(0)->setPen(QPen(Qt::blue)); // line color blue for first graph
customPlot->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20))); // first graph will be filled with translucent blue
customPlot->addGraph();
customPlot->graph(1)->setPen(QPen(Qt::red)); // line color red for second graph
// generate some points of data (y0 for first, y1 for second graph):
QVector<double> x(251), y0(251), y1(251);
for (int i=0; i<251; ++i)
{
  x[i] = i;
  y0[i] = qExp(-i/150.0)*qCos(i/10.0); // exponentially decaying cosine
  y1[i] = qExp(-i/150.0);              // exponential envelope
}
// configure right and top axis to show ticks but no labels:
// (see QCPAxisRect::setupFullAxesBox for a quicker method to do this)
customPlot->xAxis2->setVisible(true);
customPlot->xAxis2->setTickLabels(false);
customPlot->yAxis2->setVisible(true);
customPlot->yAxis2->setTickLabels(false);
// make left and bottom axes always transfer their ranges to right and top axes:
connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
// pass data points to graphs:
customPlot->graph(0)->setData(x, y0);
customPlot->graph(1)->setData(x, y1);
// let the ranges scale themselves so graph 0 fits perfectly in the visible area:
customPlot->graph(0)->rescaleAxes();
// same thing for graph 1, but only enlarge ranges (in case graph 1 is smaller than graph 0):
customPlot->graph(1)->rescaleAxes(true);
// Note: we could have also just called customPlot->rescaleAxes(); instead
// Allow user to drag axis ranges with mouse, zoom with mouse wheel and select graphs by clicking:
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);

基础API注释

addgraph

要加一个曲线时,必需先加一个graph,再在graph的基础上添加

customPlot->graph(0)->setData(x,y0);

setData

两维数据分为key与value,如果这两者被打包成VECTOR,那么setData,设置整张graph的数据

addData

用于添加一个点的数据

replot

用于重绘当前图形显示

用以上几个API基本就可以显示一张曲线图了,总体来说QCustomPlot做简单的曲线显示,还是比较好上手。当然想到实现很好的效果,还是多了解API文档及试验。
整体来说QCustomPlot的功能还是很强大,能实现很多复杂的应用。官方也提供了很的示例。

Demo工程链接

posted @ 2021-12-03 09:31  cau_par  阅读(493)  评论(0编辑  收藏  举报