├── .gitignore
├── LICENSE
├── docs
├── .nojekyll
├── README.md
├── _sidebar.md
├── index.html
└── zh-cn
│ ├── QCustomPlot之Item的移动和缩放(十二).md
│ ├── QCustomPlot之Item(十).md
│ ├── QCustomPlot之个性化外观(二).md
│ ├── QCustomPlot之参数曲线(七).md
│ ├── QCustomPlot之层和布局(四).md
│ ├── QCustomPlot之平滑曲线上(八).md
│ ├── QCustomPlot之平滑曲线下(九).md
│ ├── QCustomPlot之开始(一).md
│ ├── QCustomPlot之柱状图(三).md
│ ├── QCustomPlot之简单动态图(六).md
│ └── QCustomPlot之轴矩形和轴(五).md
└── src
├── CMakeLists.txt
├── examples
├── 001_start
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 003_bar_chart_demo
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 004_layout_demo
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 005_axisrect_demo
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 006_dynamic_data_demo
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 007_lemniscate_demo
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 008_smooth_graph_demo_01
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 009_smooth_graph_demo_02
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
├── 012_stretch_item_demo
│ ├── CMakeLists.txt
│ ├── main.cpp
│ ├── mainwindow.cpp
│ └── mainwindow.h
└── CMakeLists.txt
└── qcustomplot
├── CMakeLists.txt
├── GPL.txt
├── changelog.txt
├── qcpplot.cpp
├── qcpplot.h
├── qcpsizehandle.cpp
├── qcpsizehandle.h
├── qcpsizehandlemanager.cpp
├── qcpsizehandlemanager.h
├── qcpsmoothcurve.cpp
├── qcpsmoothcurve.h
├── qcptextbars.cpp
├── qcptextbars.h
├── qcustomplot.cpp
└── qcustomplot.h
/.gitignore:
--------------------------------------------------------------------------------
1 | bin/
2 | build*
3 | .vs/
4 | .idea/
5 | out*
6 |
7 | cmake-build*/
8 | *.txt.user
9 | *.autosave
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 梁如风
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/docs/.nojekyll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lancelot-Yagami/QCustomPlot-Manual/ca3fc5f06e037e1cc7b85b2e718a66e62f6a384e/docs/.nojekyll
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # QCustomPlot使用手册
2 |
3 | > 少年
4 | >
5 | > 我看你骨骼精奇
6 | >
7 | > 是万中无一的武学奇才
8 | >
9 | > 维护世界和平就靠你了
10 | >
11 | > 我这有本秘籍《QCustomPlot使用手册》
12 | >
13 | > 见与你有缘
14 | >
15 | > 就十块卖给你了
16 |
17 | # 注意事项
18 |
19 | 博客上的代码不是最新的,请以[源码](https://github.com/lancelot-Yagami/QCustomPlot-Manual.git)的地址为准
20 |
21 | # 博客教程
22 |
23 | - [安静阅读地址](https://lancelot-yagami.github.io/QCustomPlot-Manual)
24 | - [CSDN博客地址](https://blog.csdn.net/qq10097355/category_9801691.html)
25 | - [简书博客地址](https://www.jianshu.com/nb/43912120)
26 |
27 |
28 | # 构建
29 |
30 | 使用`QtCreator`和`CMake`进行构建,不要使用`MSVC`编译,请使用`MingW`编译
--------------------------------------------------------------------------------
/docs/_sidebar.md:
--------------------------------------------------------------------------------
1 | * [首页](README "QCustomPlot使用手册")
2 | * [QCustomPlot之开始(一)](zh-cn/QCustomPlot之开始(一) "QCustomPlot之开始(一)")
3 | * [QCustomPlot之个性化外观(二)](zh-cn/QCustomPlot之个性化外观(二) "QCustomPlot之个性化外观(二)")
4 | * [QCustomPlot之柱状图(三)](zh-cn/QCustomPlot之柱状图(三) "QCustomPlot之柱状图(三)")
5 | * [QCustomPlot之层和布局(四)](zh-cn/QCustomPlot之层和布局(四) "QCustomPlot之层和布局(四)")
6 | * [QCustomPlot之轴矩形和轴(五)](zh-cn/QCustomPlot之轴矩形和轴(五) "QCustomPlot之轴矩形和轴(五)")
7 | * [QCustomPlot之简单动态图(六)](zh-cn/QCustomPlot之简单动态图(六) "QCustomPlot之简单动态图(六)")
8 | * [QCustomPlot之参数曲线(七)](zh-cn/QCustomPlot之参数曲线(七) "QCustomPlot之参数曲线(七)")
9 | * [QCustomPlot之平滑曲线上(八)](zh-cn/QCustomPlot之平滑曲线上(八) "QCustomPlot之平滑曲线上(八)")
10 | * [QCustomPlot之平滑曲线下(九)](zh-cn/QCustomPlot之平滑曲线下(九) "QCustomPlot之平滑曲线下(九)")
11 | * [QCustomPlot之Item(十)](zh-cn/QCustomPlot之Item(十) "QCustomPlot之Item(十)")
12 | * [QCustomPlot之Item的移动和缩放(十二)](zh-cn/QCustomPlot之Item的移动和缩放(十二) "QCustomPlot之Item的移动和缩放(十二)")
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | QCustomPlot使用手册
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之Item的移动和缩放(十二).md:
--------------------------------------------------------------------------------
1 | 首先看一下效果图
2 | 
3 |
4 | #### 移动
5 | Item移动的主要思想是改变Item下所有QCPItemPosition的位置来达到移动的目的
6 |
7 | ```C++
8 | void QCPSizeHandleManager::onItemMove(QCPAbstractItem *item, const QPointF &delta)
9 | {
10 | if (!item || !mItems.contains(item))
11 | return;
12 |
13 | auto itemData = mItems.value(item);
14 | if (!itemData->movable)
15 | return;
16 |
17 | for (auto position : item->positions())
18 | position->setPixelPosition(position->pixelPosition() + delta);
19 | }
20 | ```
21 |
22 | #### 缩放
23 | 与移动稍微不同的是,缩放只是移动一个QCPItemPosition的位置就可以了,不过为了让缩放点可视化,我们在缩放点位置新增了一个QCPSizeHandle,QCPSizeHandle是一个自定义的Item,如果你还不会自定义Item,请看上篇[QCustomPlot之鼠标悬浮显示值(十一)](https://blog.csdn.net/qq10097355/article/details/105048146)
24 |
25 | ```C++
26 | void QCPSizeHandleManager::onItemResize(QCPSizeHandle *sizeHandle, const QPointF &delta)
27 | {
28 | if (!sizeHandle)
29 | return;
30 |
31 | auto itemData = mItems.value(sizeHandle->attachItem());
32 | if (!itemData || !itemData->resizable)
33 | return;
34 |
35 | if (auto parentPosition = static_cast(sizeHandle->position->parentAnchor()))
36 | {
37 | parentPosition->setPixelPosition(parentPosition->pixelPosition() + delta);
38 | }
39 | }
40 | ```
41 |
42 | 具体请查看[源码](https://github.com/lancelot-Yagami/QCustomPlot-Manual/tree/main/src/examples/012_stretch_item_demo)
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之Item(十).md:
--------------------------------------------------------------------------------
1 | 在QCustomPlot中,所有的Item都继承自`QCPAbstractItem`,QCustomPlot给我们提供了一些Item
2 |
3 | 
4 |
5 | - QCPItemBracket 括号Item
6 | - QCPItemCurve 曲线Item,其实就是贝塞尔曲线
7 | - QCPItemEllipse 椭圆/圆Item
8 | - QCPItemLine 线段Item
9 | - QCPItemPixmap 图片Item
10 | - QCPItemRect 矩形Item
11 | - QCPItemStraightLine 直线Item
12 | - QCPItemText 文字Item
13 | - QCPItemTracer 追踪者Item
14 |
15 | `QCPAbstractItem`默认存在于`QCustomPlot`的当前层中,默认的当前层为`main`,我们可以通过`setClipToAxisRect`和`setClipAxisRect`设置Item裁切于某个特定的轴矩形,将`setClipToAxisRect`设置为false则Item裁切于`QCustomPlot`
16 |
17 | #### QCPItemAnchor与QCPItemPosition联系与区别
18 | QCPItemPosition继承自QCPItemAnchor,QCPItemAnchor用于给QCPItemPosition定位用的,QCPItemPosition则表示了Item的位置,一个Item可以有多个QCPItemAnchor和QCPItemPosition
19 | 我们主要理解QCPItemPosition是如何决定Item的位置的,它有四种位置类型:
20 | - ptAbsolute 按像素的方式
21 | - ptViewportRatio 按QCustomPlot可视区域的比例
22 | - ptAxisRectRatio 按其存在的轴矩形的比例(通过`setAxisRect`函数设置轴矩形)
23 | - ptPlotCoords 按坐标系位置(通过`setAxes`函数轴)
24 |
25 | 可以通过`setType`、`setTypeX`、`setTypeY`函数设置x、y方向的位置类型,然后通过`setCoords`设置其位置,`setCoords`是跟`setType`设置的类型相关的,Item的位置还跟它锚定的父锚点QCPItemAnchor相关,可以通过`setParentAnchor`、`setParentAnchorX`、`setParentAnchorY`函数设置x、y方向的父锚点,父锚点决定了其起点位置,**当设置父锚点后,type类型会变为ptAbsolute按像素的方式**
26 |
27 | 我们可以直接通过`setPixelPosition`设置Item的像素位置,而不用管`setType`的类型是什么,通过`pixelPosition`返回Item的像素位置
28 |
29 | **以下图片空心圆为QCPItemAnchor,实心圆为QCPItemPosition**
30 | #### QCPItemBracket
31 |
32 | 
33 | 可以看到QCPItemBracket通过`left`和`right`决定其位置,而`center`则用于给其它的QCPItemPosition定位用的,QCPItemBracket通过`setLength`设置`left`/`right`到`center`的垂直距离(像素)
34 | 
35 |
36 | QCPItemBracket有四种类型:
37 | - bsSquare 中括号
38 | - bsRound 小括号
39 | - bsCurly 大括号
40 | - bsCalligraphic 实体大括号
41 |
42 | #### QCPItemCurve
43 |
44 | 
45 | 可以看到QCPItemCurve有四个点决定其位置起点`start`和终点`end`以及两个控制点`startDir`、`endDir`,理解QCPItemCurve的位置需要我们对贝塞尔曲线有所理解
46 |
47 | #### QCPItemText
48 |
49 | 
50 | 可以看到QCPItemText由`position`决定其位置,但是`position`不一定是在文字中心的位置,我们可以通过`setPositionAlignment
51 | `设置`position`对齐在文字的哪一个地方,比如要对齐在`topLeft`的位置:setPositionAlignment(Qt::AlignLeft)
52 |
53 | #### QCPItemTracer
54 | tracer是比较常用的一个Item,它主要用来实时跟踪`QCPGraph`的某个数据点,QCPItemTracer也是用一个`position`来决定其位置
55 |
56 | 
57 |
58 | QCPItemTracer有五种风格
59 | - tsNone 不显示tracer
60 | - tsPlus 加号
61 | - tsCrosshair 十字线,横跨整个轴矩形
62 | - tsCircle 圆
63 | - tsSquare 方块
64 |
65 | QCPItemTracer通过函数`setGraph`和`setGraphKey`设置要跟踪的图表以及数据点,`setGraph(nullptr)`可以使QCPItemTracer得位置是任意的。QCPItemTracer的位置还跟`setInterpolating`函数有关,当`setInterpolating`为true时,启用线性插值,这时候QCPItemTracer的位置是精确地在我们设置的位置,并且对`value`轴的值进行线性插值;为false的时候QCPItemTracer的位置是最接近于这个位置的`key`值点的位置
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之个性化外观(二).md:
--------------------------------------------------------------------------------
1 | QCustomPlot可以制作出优美的图表,它提供了大量可以自定义风格的接口
2 |
3 | #### 设置QCustomPlot的背景颜色
4 | ```
5 | QLinearGradient plotGradient;
6 | plotGradient.setStart(0, 0);
7 | plotGradient.setFinalStop(0, 350);
8 | plotGradient.setColorAt(0, QColor(80, 80, 80));
9 | plotGradient.setColorAt(1, QColor(50, 50, 50));
10 | customPlot->setBackground(plotGradient); // 设置背景颜色
11 | ```
12 | 
13 |
14 |
15 | #### 设置QCPAxisRect轴矩形的背景颜色
16 | ```
17 | QLinearGradient axisRectGradient;
18 | axisRectGradient.setStart(0, 0);
19 | axisRectGradient.setFinalStop(0, 350);
20 | axisRectGradient.setColorAt(0, QColor(80, 80, 80));
21 | axisRectGradient.setColorAt(1, QColor(30, 30, 30));
22 | customPlot->axisRect()->setBackground(axisRectGradient); // 设置QCPAxisRect背景颜色
23 | ```
24 |
25 | 
26 |
27 |
28 | #### 设置QCPAxis轴的风格
29 | ```
30 | customPlot->xAxis->setBasePen(QPen(Qt::white, 1)); // 轴线的画笔
31 | customPlot->xAxis->setTickPen(QPen(Qt::white, 1)); // 轴刻度线的画笔
32 | customPlot->xAxis->setSubTickPen(QPen(Qt::white, 1)); // 轴子刻度线的画笔
33 | customPlot->xAxis->setTickLabelColor(Qt::white); // 轴刻度文字颜色
34 | customPlot->xAxis->setLabel("标签"); // 只有设置了标签,轴标签的颜色才会显示
35 | customPlot->xAxis->setLabelColor(Qt::white); // 轴标签颜色
36 | customPlot->xAxis->setTickLengthIn(3); // 轴线内刻度的长度
37 | customPlot->xAxis->setTickLengthOut(5); // 轴线外刻度的长度
38 | customPlot->xAxis->setUpperEnding(QCPLineEnding::esSpikeArrow); // 设置轴线结束时的风格为 实角三角形但内部有凹陷的形状, setLowerEnding设置轴线开始时的风格
39 | ```
40 |
41 | 
42 |
43 |
44 | #### 设置QCPGrid网格的风格
45 | ```
46 | // 每条网格对应一个刻度
47 | customPlot->xAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine)); // 网格线(对应刻度)画笔
48 | customPlot->yAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
49 | customPlot->xAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine)); // 子网格线(对应子刻度)画笔
50 | customPlot->yAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
51 | customPlot->xAxis->grid()->setSubGridVisible(true); // 显示子网格线
52 | customPlot->yAxis->grid()->setSubGridVisible(true);
53 | customPlot->xAxis->grid()->setZeroLinePen(QPen(Qt::red)); // 设置刻度为0时的网格线的画笔
54 | customPlot->yAxis->grid()->setZeroLinePen(QPen(Qt::red));
55 | ```
56 | 
57 |
58 |
59 | #### 图表的风格
60 | ```
61 | QPen pen;
62 | QStringList lineNames;
63 | lineNames << "lsNone" << "lsLine" << "lsStepLeft" << "lsStepRight" << "lsStepCenter" << "lsImpulse";
64 |
65 | for (int i = QCPGraph::lsNone; i <= QCPGraph::lsImpulse; ++i)
66 | {
67 | customPlot->addGraph();
68 | pen.setColor(QColor(qSin(i*1+1.2)*80+80, qSin(i*0.3+0)*80+80, qSin(i*0.3+1.5)*80+80));
69 | customPlot->graph()->setPen(pen); // 设置图表的画笔
70 | customPlot->graph()->setName(lineNames.at(i-QCPGraph::lsNone));
71 | customPlot->graph()->setLineStyle((QCPGraph::LineStyle)i); // 设置图表线段的风格
72 | customPlot->graph()->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5)); // 设置图表散点图的样式,散点图的样式有很多种,可以自己试试
73 |
74 | QVector x(15), y(15);
75 | for (int j=0; j<15; ++j)
76 | {
77 | x[j] = j/15.0 * 5*3.14 + 0.01;
78 | y[j] = 7*qSin(x[j])/x[j] - (i-QCPGraph::lsNone)*5 + (QCPGraph::lsImpulse)*5 + 2;
79 | }
80 | customPlot->graph()->setData(x, y);
81 | customPlot->graph()->rescaleAxes(true);
82 | }
83 | ```
84 |
85 | 
86 |
87 |
88 | #### 图表画刷
89 | ```
90 | // 第一种:与0刻度线围成区域
91 | customPlot->addGraph();
92 | customPlot->graph(0)->setPen(QPen(Qt::blue));
93 | customPlot->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20)));
94 | customPlot->addGraph();
95 | customPlot->graph(1)->setPen(QPen(Qt::red));
96 |
97 | // 第二种方式:与其它图围成区域,使用的是图0的画刷
98 | // customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1)); // 将图0与图1围成区域
99 | ```
100 | 
101 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之参数曲线(七).md:
--------------------------------------------------------------------------------
1 | `QCPCurve`用于绘制参数方程曲线,常见的参数方程有以下几种:
2 |
3 | 
4 |
5 | `QCPCurve`与`QCPGraph`的区别在于它引入了第三个坐标`t`,而`QCPGraph`只有x,y两个坐标,这是因为在参数方程曲线中,可能会有多个点对应同个key坐标,而`t`坐标的引入决定了参数方程x,y坐标的顺序,这样就不会混乱
6 |
7 | 在数据方面,`t`坐标在QCPCurve表现为排序键`sortKey`,`x`坐标表现为主键`mainKey`,`y`坐标表现为`mainValue`,而在QCPGraph中排序键`sortKey`和主键`mainKey`都是`x`坐标,`y`坐标表现为`mainValue`
8 |
9 | #### 参数方程的使用
10 |
11 | ```
12 | void MainWindow::setupLemniscateDemo(QCustomPlot *customPlot)
13 | {
14 | QCPCurve *curve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);
15 | curve->setPen(QPen(Qt::red));
16 |
17 | // 由于我们是动态图,并且其范围不变化,所以预先设置好了范围
18 | customPlot->xAxis->setRange(-2.5, 12.5);
19 | customPlot->yAxis->setRange(-2.8, 2.8);
20 |
21 | connect(&dataTimer, SIGNAL(timeout()), this, SLOT(dynamicLemniscateSlot()));
22 | dataTimer.start(10); // 10ms刷新一次,实际上QTimer可能达不到这个精度
23 | }
24 | ```
25 |
26 | 参数方程来自:[伯努利双纽线(无穷大的符号)](https://blog.csdn.net/stereohomology/article/details/45528463)
27 | ```
28 | void MainWindow::dynamicLemniscateSlot()
29 | {
30 | static double t = -M_PI; // 定义起始t
31 | static bool reversed = false; // 为了重复绘制
32 |
33 | QCPCurve *curve = static_cast(ui->customPlot->plottable(0));
34 |
35 | // 伯努利双纽线(无穷大的符号)
36 | double x = -686*qCos(t) + 735*qCos(2*t) + 490*qSqrt(qPow(qSin(t), 4)) - 265;
37 | x /= (280*qCos(t) - 298);
38 | double y = 5*qSqrt(qPow(qSin(t), 4))*(10/qSin(t) - 7/qTan(t)) + 3*(35*qCos(t) - 33)*qSin(t);
39 | y = 7*y/(140*qCos(t) - 149);
40 |
41 | if (!reversed) { // 还未绘制完成
42 | t += 0.01;
43 | curve->data()->add(QCPCurveData(t, x, y));
44 | } else { // 绘制已经完成,倒退回去
45 | t -= 0.01;
46 | curve->data()->removeAfter(t); // 这里不能用remove,因为精度原因,remove并不能精确匹配,导致无法删除数据点
47 | }
48 |
49 | ui->customPlot->replot();
50 |
51 | // 重复绘制
52 | if (t >= M_PI) {
53 | t = M_PI;
54 | reversed = true;
55 | } else if (reversed && t <= -M_PI) {
56 | t = -M_PI;
57 | reversed = false;
58 | }
59 | }
60 | ```
61 |
62 |
63 | 
64 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之层和布局(四).md:
--------------------------------------------------------------------------------
1 | #### 层和层元素
2 |
3 | 在QCustomPlot中,一切可显示的对象都是继承自层元素`QCPLayerable`,层`QCPLayer`则管理着层元素,QCustomPlot利用层决定了不同元素的绘制顺序
4 | 层有两种刷新模式:
5 | - lmLogical 只用于渲染的顺序,并且与`相邻`的lmLogical层共享绘图缓存(注意这里的相邻,如果前一个层是`lmBuffered`模式,则会新建一个绘图缓存用于绘图)
6 | - lmBuffered 层拥有自己的绘图缓存,并且可以单独的刷新(调用`QCPLayer::replot`函数)
7 |
8 | 默认只有`overlay`层启用了`lmBuffered`单独绘制机制,其它层都共享一个绘图缓存,因为`overlay`层主要是用于存放悬浮与图表上的item项,需要频繁的刷新,启用了`lmBuffered`的层会多占用内存
9 |
10 | #### 布局和布局元素
11 | 在QCustomPlot中,布局方式只有两种:
12 |
13 | * QCPLayoutGrid 网格布局
14 | * QCPLayoutInset 内嵌式布局, 这种布局的作用是把子元素与布局的边界对齐或者将其放置在布局内的任意位置(图例QCPLegend就被放置在此布局内),严格来说这个并不算布局
15 |
16 | 我们可以看下继承关系图,可以看到这两种布局都继承自`QCPLayout`,而`QCPLayout`继承自`QCPLayoutElement`布局元素,所以一个布局可以包含另一个布局,布局内的元素都要继承自`QCPLayoutElement`
17 |
18 | 
19 |
20 |
21 | 在QCustomPlot里面维护着一个网格布局,默认只有一个QCPAxisRect元素,而QCPAxisRect里则维护这一个内嵌式的布局,用于放置图例QCPLegend
22 |
23 | ```
24 | mPlotLayout = new QCPLayoutGrid;
25 | mPlotLayout->initializeParentPlot(this);
26 | mPlotLayout->setParent(this);
27 | mPlotLayout->setLayer(QLatin1String("main")); // 设置网格布局的层为main层
28 |
29 | QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
30 | mPlotLayout->addElement(0, 0, defaultAxisRect);
31 | xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
32 | yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
33 | xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
34 | yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
35 | legend = new QCPLegend;
36 | legend->setVisible(false); // 默认不显示图例
37 | defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight | Qt::AlignTop); // 设置图例对齐于QCPAxisRect的右上角
38 | defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); // 设置布局的外边距
39 |
40 | defaultAxisRect->setLayer(QLatin1String("background")); // QCPAxisRect的层设置为background层
41 | ```
42 |
43 | 于是我们可以设置图例的位置
44 | ```
45 | customPlot->legend->setVisible(true); // 因为图例默认为隐藏的,所以让其显示
46 | customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignHCenter); // 对齐于QCPAxisRect中间的顶部
47 |
48 | // 以任意位置的方式放置图例,解开以下的注释查看效果
49 | // customPlot->axisRect()->insetLayout()->setInsetPlacement(0, QCPLayoutInset::ipFree);
50 | // customPlot->axisRect()->insetLayout()->setInsetRect(0, QRectF(0.6, 0.0, 0.2, 0.2)); // 这里按比例给出图例的位置,在QCPAxisRect的(60%,40%)的位置,宽高分别为QCPAxisRect的(20%,20%)宽高的大小
51 | ```
52 |
53 | 
54 | 
55 |
56 |
57 | 我们甚至可以把它放置在QCustomPlot中,而不是在QCPAxisRect中,但是这种做法不太可取,just for fun :)
58 |
59 | ```
60 | customPlot->plotLayout()->setMargins(QMargins(0, 0, 0, 30)); // 首先为底部预留出足够的空间
61 | customPlot->axisRect()->insetLayout()->setInsetPlacement(0, QCPLayoutInset::ipFree); // 设置以任意位置放置图例,以对齐边界的方式不行
62 | customPlot->axisRect()->insetLayout()->setInsetRect(0, QRectF(0.0, 1.2, 1.0, 0.1)); // 将y方向的位置设置为超过1以便它的位置超过QCPAxisRect的位置
63 | ```
64 |
65 | 
66 |
67 | 其实我们还可以将图例放置在QCustomPlot的网格布局中,这样也可以将图例放置在QCustomPlot中,但这种方法写起来比较麻烦,这里就不讲解了
68 |
69 |
70 | #### 为图表添加标题
71 |
72 | 有了布局,我们可以为所欲为,添加标题很简单,仅需`QCPTextElement`类即可,它也是一个布局元素
73 | ```
74 | customPlot->plotLayout()->insertRow(0); // 插入一行
75 | customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, "Regenerative Energies", QFont("sans", 12, QFont::Bold))); // 在第一行第一列添加标题
76 |
77 | ```
78 |
79 | 
80 |
81 |
82 | #### 为图例添加标题
83 | `QCPLegend`继承自`QCPLayoutGrid`,所以我们也很容易为图例添加一个标题
84 |
85 | ```
86 | QCPTextElement *title = new QCPTextElement(ui->customPlot, "这是图例标题", QFont("sans", 10, QFont::Bold));
87 | title->setMargins(QMargins(0, 6, 0, 10)); // 为了效果更好,添加一些边距
88 | title->setLayer("legend"); // 一定要把标题的层设置为legend层
89 |
90 | customPlot->legend->insertRow(0); // 插入一行
91 | customPlot->legend->addElement(0, 0, title); // 在第一行第一列添加标题
92 | ```
93 |
94 | 
95 |
96 | #### 横向图例
97 | 只需将图例布局的填充顺序改为以列的方式(图例默认是以行的方式,所以是竖向的)
98 | ```
99 | customPlot->legend->setFillOrder(QCPLayoutGrid::foColumnsFirst);
100 | ```
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之平滑曲线上(八).md:
--------------------------------------------------------------------------------
1 | 在QCustomPlot中,并没有为我们提供平滑曲线,所以需要我们改造它
2 |
3 | #### 一、生成平滑曲线
4 | **2020-6-6日更新修复当数据中有NaN的数据时平滑曲线的显示问题**
5 | 来源:[公孙二狗](https://qtdebug.com/qtbook-paint-smooth-curve/) ,在这里感谢狗哥
6 | 生成平滑曲线的方法我也不知道,反正拿来用就是了
7 | ```
8 | class SmoothCurveGenerator
9 | {
10 | protected:
11 | static QPainterPath generateSmoothCurveImp(const QVector &points) {
12 | QPainterPath path;
13 | int len = points.size();
14 |
15 | if (len < 2) {
16 | return path;
17 | }
18 |
19 | QVector firstControlPoints;
20 | QVector secondControlPoints;
21 | calculateControlPoints(points, &firstControlPoints, &secondControlPoints);
22 |
23 | path.moveTo(points[0].x(), points[0].y());
24 |
25 | // Using bezier curve to generate a smooth curve.
26 | for (int i = 0; i < len - 1; ++i) {
27 | path.cubicTo(firstControlPoints[i], secondControlPoints[i], points[i+1]);
28 | }
29 |
30 | return path;
31 | }
32 | public:
33 | static QPainterPath generateSmoothCurve(const QVector &points) {
34 | QPainterPath result;
35 |
36 | int segmentStart = 0;
37 | int i = 0;
38 | int pointSize = points.size();
39 | while (i < pointSize) {
40 | if (qIsNaN(points.at(i).y()) || qIsNaN(points.at(i).x()) || qIsInf(points.at(i).y())) {
41 | QVector lineData(QVector(points.constBegin() + segmentStart, points.constBegin() + i - segmentStart));
42 | result.addPath(generateSmoothCurveImp(lineData));
43 | segmentStart = i + 1;
44 | }
45 | ++i;
46 | }
47 | QVector lineData(QVector(points.constBegin() + segmentStart, points.constEnd()));
48 | result.addPath(generateSmoothCurveImp(lineData));
49 | return result;
50 | }
51 |
52 | static QPainterPath generateSmoothCurve(const QPainterPath &basePath, const QVector &points) {
53 | if (points.isEmpty()) return basePath;
54 |
55 | QPainterPath path = basePath;
56 | int len = points.size();
57 | if (len == 1) {
58 | path.lineTo(points.at(0));
59 | return path;
60 | }
61 |
62 | QVector firstControlPoints;
63 | QVector secondControlPoints;
64 | calculateControlPoints(points, &firstControlPoints, &secondControlPoints);
65 |
66 | path.lineTo(points.at(0));
67 | for (int i = 0; i < len - 1; ++i)
68 | path.cubicTo(firstControlPoints[i], secondControlPoints[i], points[i+1]);
69 |
70 | return path;
71 | }
72 |
73 | static void calculateFirstControlPoints(double *&result, const double *rhs, int n) {
74 | result = new double[n];
75 | double *tmp = new double[n];
76 | double b = 2.0;
77 | result[0] = rhs[0] / b;
78 |
79 | // Decomposition and forward substitution.
80 | for (int i = 1; i < n; i++) {
81 | tmp[i] = 1 / b;
82 | b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
83 | result[i] = (rhs[i] - result[i - 1]) / b;
84 | }
85 |
86 | for (int i = 1; i < n; i++) {
87 | result[n - i - 1] -= tmp[n - i] * result[n - i]; // Backsubstitution.
88 | }
89 |
90 | delete[] tmp;
91 | }
92 |
93 | static void calculateControlPoints(const QVector &knots,
94 | QVector *firstControlPoints,
95 | QVector *secondControlPoints) {
96 | int n = knots.size() - 1;
97 |
98 | firstControlPoints->reserve(n);
99 | secondControlPoints->reserve(n);
100 |
101 | for (int i = 0; i < n; ++i) {
102 | firstControlPoints->append(QPointF());
103 | secondControlPoints->append(QPointF());
104 | }
105 |
106 | if (n == 1) {
107 | // Special case: Bezier curve should be a straight line.
108 | // P1 = (2P0 + P3) / 3
109 | (*firstControlPoints)[0].rx() = (2 * knots[0].x() + knots[1].x()) / 3;
110 | (*firstControlPoints)[0].ry() = (2 * knots[0].y() + knots[1].y()) / 3;
111 |
112 | // P2 = 2P1 – P0
113 | (*secondControlPoints)[0].rx() = 2 * (*firstControlPoints)[0].x() - knots[0].x();
114 | (*secondControlPoints)[0].ry() = 2 * (*firstControlPoints)[0].y() - knots[0].y();
115 |
116 | return;
117 | }
118 |
119 | // Calculate first Bezier control points
120 | double *xs = nullptr;
121 | double *ys = nullptr;
122 | double *rhsx = new double[n]; // Right hand side vector
123 | double *rhsy = new double[n]; // Right hand side vector
124 |
125 | // Set right hand side values
126 | for (int i = 1; i < n - 1; ++i) {
127 | rhsx[i] = 4 * knots[i].x() + 2 * knots[i + 1].x();
128 | rhsy[i] = 4 * knots[i].y() + 2 * knots[i + 1].y();
129 | }
130 | rhsx[0] = knots[0].x() + 2 * knots[1].x();
131 | rhsx[n - 1] = (8 * knots[n - 1].x() + knots[n].x()) / 2.0;
132 | rhsy[0] = knots[0].y() + 2 * knots[1].y();
133 | rhsy[n - 1] = (8 * knots[n - 1].y() + knots[n].y()) / 2.0;
134 |
135 | // Calculate first control points coordinates
136 | calculateFirstControlPoints(xs, rhsx, n);
137 | calculateFirstControlPoints(ys, rhsy, n);
138 |
139 | // Fill output control points.
140 | for (int i = 0; i < n; ++i) {
141 | (*firstControlPoints)[i].rx() = xs[i];
142 | (*firstControlPoints)[i].ry() = ys[i];
143 |
144 | if (i < n - 1) {
145 | (*secondControlPoints)[i].rx() = 2 * knots[i + 1].x() - xs[i + 1];
146 | (*secondControlPoints)[i].ry() = 2 * knots[i + 1].y() - ys[i + 1];
147 | } else {
148 | (*secondControlPoints)[i].rx() = (knots[n].x() + xs[n - 1]) / 2;
149 | (*secondControlPoints)[i].ry() = (knots[n].y() + ys[n - 1]) / 2;
150 | }
151 | }
152 |
153 | delete xs;
154 | delete ys;
155 | delete[] rhsx;
156 | delete[] rhsy;
157 | }
158 | };
159 | ```
160 |
161 | #### 二、drawLinePlot函数的修改
162 |
163 | `mSmooth`为我们添加的一个`bool`型的类成员变量,并且我们限制了`QCPGraph`的线风格`mLineStyle`为`lsLine`的时候才会真正的绘制平滑曲线
164 | ```
165 | void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector &lines) const
166 | {
167 | if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) {
168 | applyDefaultAntialiasingHint(painter);
169 | if (mSmooth && mLineStyle == lsLine) painter->drawPath(SmoothCurveGenerator::generateSmoothCurve(lines));
170 | else drawPolyline(painter, lines);
171 | }
172 | }
173 | ```
174 |
175 | 这时候已经可以实现平滑曲线了,来个简单的例子看下
176 | ```
177 | void MainWindow::setupSmoothCurveDemo(QCustomPlot *customPlot)
178 | {
179 | QVector xdata = { 1, 2, 3, 4, 5, 6, 7 };
180 | QVector ydata = { 820, 932, 901, 934, 1290, 1330, 1320 };
181 |
182 | QCPSmoothCurve *graph = new QCPSmoothCurve(customPlot->xAxis, customPlot->yAxis);
183 | graph->setPen(QPen(Qt::red, 2));
184 | graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor(Qt::red), QColor(Qt::white), 6));
185 | graph->setData(xdata, ydata);
186 | graph->setSmooth(true); // 开启平滑曲线
187 |
188 | customPlot->xAxis->setRange(0, 8);
189 | customPlot->yAxis->setRange(0, 1500);
190 | }
191 | ```
192 | 
193 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之平滑曲线下(九).md:
--------------------------------------------------------------------------------
1 | 接上篇[QCustomPlot之平滑曲线上(八)](zh-cn/QCustomPlot之平滑曲线上(八)),上篇只是实现了平滑曲线的绘制,但是并没有实现平滑曲线与0点线之间的填充区域以及两个`QCPGraph`之间的填充区域,我们将在这里实现它们
2 |
3 | #### drawFill函数的修改
4 | ```
5 | void QCPSmoothCurve::drawFill(QCPPainter *painter, QVector *lines) const
6 | {
7 | if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
8 | if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
9 |
10 | applyFillAntialiasingHint(painter);
11 | QVector segments = getNonNanSegments(lines, keyAxis()->orientation());
12 | if (!mChannelFillGraph) // 与0点线围成的区域
13 | {
14 | // draw base fill under graph, fill goes all the way to the zero-value-line:
15 | for (int i=0; idrawPath(getSmoothFillPath(lines, segments.at(i))); // 平滑曲线
18 | else
19 | painter->drawPolygon(getFillPolygon(lines, segments.at(i))); // 折线
20 | } else // 与其它QCPGraph围成的区域
21 | {
22 | // draw fill between this graph and mChannelFillGraph:
23 | auto channelFillGraph = qobject_cast(mChannelFillGraph.data());
24 | if (!channelFillGraph) {
25 | qDebug() << "ChannelFillGraph must be QCPSmoothCurve";
26 | return;
27 | }
28 | QVector otherLines;
29 | channelFillGraph->getLines(&otherLines, QCPDataRange(0, channelFillGraph->dataCount()));
30 | if (!otherLines.isEmpty())
31 | {
32 | QVector otherSegments = getNonNanSegments(&otherLines, channelFillGraph->keyAxis()->orientation());
33 | QVector > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
34 | for (int i=0; imLineStyle == lsLine)
36 | painter->drawPath(getSmoothChannelFillPath(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); // 平滑曲线
37 | else
38 | painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); // 折线
39 | }
40 | }
41 | }
42 | }
43 | ```
44 |
45 | #### 与0点线之间的填充区域
46 |
47 | ```
48 | QPainterPath QCPSmoothCurve::getSmoothFillPath(const QVector *lineData, QCPDataRange segment) const
49 | {
50 | // 只有一个点构不成填充区域
51 | if (segment.size() < 2)
52 | return QPainterPath();
53 |
54 | // 起点,终点对应在轴上的位置
55 | QPointF start = getFillBasePoint(lineData->at(segment.begin()));
56 | QPointF end = getFillBasePoint(lineData->at(segment.end() - 1));
57 |
58 | // 将平滑曲线连成一个封闭区域
59 | QPainterPath path = SmoothCurveGenerator::generateSmoothCurve(*lineData);
60 | path.lineTo(end);
61 | path.lineTo(start);
62 | path.lineTo(lineData->at(segment.begin()));
63 | return path;
64 | }
65 | ```
66 |
67 | 
68 |
69 |
70 | #### 与其它QCPGraph围成的区域
71 | `getSmoothChannelFillPath`基本是从`getChannelFillPolygon`复制过来的,我们在这上面进行修改,修改的内容我都有注释
72 | ```
73 | QPainterPath QCPSmoothCurve::getSmoothChannelFillPath(const QVector *thisData, QCPDataRange thisSegment,
74 | const QVector *otherData, QCPDataRange otherSegment) const
75 | {
76 | QPainterPath result;
77 | auto channelFillGraph = qobject_cast(mChannelFillGraph.data());
78 | if (!channelFillGraph) {
79 | qDebug() << "ChannelFillGraph must be QCPSmoothCurve";
80 | return result;
81 | }
82 |
83 | QCPAxis *keyAxis = mKeyAxis.data();
84 | QCPAxis *valueAxis = mValueAxis.data();
85 | if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
86 | if (!channelFillGraph->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return result; }
87 |
88 | if (channelFillGraph->mKeyAxis.data()->orientation() != keyAxis->orientation())
89 | return result; // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
90 |
91 | if (thisData->isEmpty()) return result;
92 | QVector thisSegmentData(thisSegment.size());
93 | QVector otherSegmentData(otherSegment.size());
94 | std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
95 | std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
96 | // pointers to be able to swap them, depending which data range needs cropping:
97 | QVector *staticData = &thisSegmentData;
98 | QVector *croppedData = &otherSegmentData;
99 |
100 | //! [1] 以下为添加的内容
101 | result = SmoothCurveGenerator::generateSmoothCurve(thisSegmentData);
102 | if (channelFillGraph->mSmooth && channelFillGraph->mLineStyle == lsLine) { // mChannelFillGraph也是平滑曲线
103 | QVector otherSegmentDataReverse(otherSegmentData.size());
104 | for (int i = otherSegmentData.size() - 1; i >= 0; --i)
105 | otherSegmentDataReverse[otherSegmentData.size() - i - 1] = otherSegmentData.at(i);
106 | result = SmoothCurveGenerator::generateSmoothCurve(result, otherSegmentDataReverse);
107 | } else { // mChannelFillGraph 是折线
108 | // mLineStyle != lsLine 会导致闪烁,目前还不知道什么原因造成
109 | for (int i = otherSegmentData.size() - 1; i >= 0; --i)
110 | result.lineTo(otherSegmentData.at(i));
111 | }
112 | //! [1]
113 |
114 | // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
115 | if (keyAxis->orientation() == Qt::Horizontal)
116 | {
117 | // x is key
118 | // crop lower bound:
119 | if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
120 | qSwap(staticData, croppedData);
121 | const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
122 | if (lowBound == -1) return result; // key ranges have no overlap
123 | //! [2] 以下为添加的内容
124 | QPointF firstPoint = QPointF(croppedData->at(0).x(), valueAxis->coordToPixel(valueAxis->range().upper)); // 注意这里只裁剪到了轴矩形的可见区域
125 | //! [2]
126 | croppedData->remove(0, lowBound);
127 | // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
128 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
129 | double slope;
130 | if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
131 | slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
132 | else
133 | slope = 0;
134 | (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
135 | (*croppedData)[0].setX(staticData->first().x());
136 |
137 | //! [3] 以下为添加的内容
138 | QPointF lastPoint = QPointF(staticData->first().x(), valueAxis->coordToPixel(valueAxis->range().lower)); // 注意这里只裁剪到了轴矩形的可见区域
139 | QPainterPath droppedPath;
140 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
141 | result -= droppedPath; // 裁掉多余区域
142 | //! [3]
143 |
144 | // crop upper bound:
145 | if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
146 | qSwap(staticData, croppedData);
147 | int highBound = findIndexAboveX(croppedData, staticData->last().x());
148 | if (highBound == -1) return result; // key ranges have no overlap
149 | //! [4] 以下为添加的内容
150 | firstPoint = QPointF(croppedData->last().x(), valueAxis->coordToPixel(valueAxis->range().lower)); // 注意这里只裁剪到了轴矩形的可见区域
151 | //! [4]
152 | croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
153 | // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
154 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
155 | const int li = croppedData->size()-1; // last index
156 | if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
157 | slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
158 | else
159 | slope = 0;
160 | (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
161 | (*croppedData)[li].setX(staticData->last().x());
162 |
163 | //! [5] 以下为添加的内容
164 | lastPoint = QPointF(staticData->last().x(), valueAxis->coordToPixel(valueAxis->range().upper));
165 | droppedPath = QPainterPath();
166 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
167 | result -= droppedPath; // 裁掉多余区域
168 | //! [5]
169 | } else // mKeyAxis->orientation() == Qt::Vertical
170 | {
171 | // y is key
172 | // crop lower bound:
173 | if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
174 | qSwap(staticData, croppedData);
175 | int lowBound = findIndexBelowY(croppedData, staticData->first().y());
176 | if (lowBound == -1) return result; // key ranges have no overlap
177 | //! [6] 以下为添加的内容
178 | QPointF firstPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().upper), croppedData->first().y());
179 | //! [6]
180 | croppedData->remove(0, lowBound);
181 | // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
182 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
183 | double slope;
184 | if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
185 | slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
186 | else
187 | slope = 0;
188 | (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
189 | (*croppedData)[0].setY(staticData->first().y());
190 |
191 | //! [7] 以下为添加的内容
192 | QPointF lastPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().lower), staticData->first().y());
193 | QPainterPath droppedPath;
194 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
195 | result -= droppedPath;
196 | //! [7]
197 |
198 | // crop upper bound:
199 | if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
200 | qSwap(staticData, croppedData);
201 | int highBound = findIndexAboveY(croppedData, staticData->last().y());
202 | if (highBound == -1) return result; // key ranges have no overlap
203 | //! [8] 以下为添加的内容
204 | firstPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().lower), croppedData->last().y());
205 | //! [8]
206 | croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
207 | // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
208 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
209 | int li = croppedData->size()-1; // last index
210 | if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
211 | slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
212 | else
213 | slope = 0;
214 | (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
215 | (*croppedData)[li].setY(staticData->last().y());
216 |
217 | //! [9] 以下为添加的内容
218 | lastPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().upper), staticData->last().y());
219 | droppedPath = QPainterPath();
220 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
221 | result -= droppedPath;
222 | //! [9]
223 | }
224 | return result;
225 | }
226 | ```
227 |
228 | 
229 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之开始(一).md:
--------------------------------------------------------------------------------
1 | ## 一、前言
2 | QCustomPlot是Qt的一个小型第三方图表库,支持静态/动态曲线、柱状图、蜡烛图、频谱图等。使用方便,
3 |
4 | 使用方法:
5 | * 直接使用:包含qcustomplot.h和qcustomplot.cpp文件即可
6 | * 生成动态库使用:在生成动态库时定义宏:`QCUSTOMPLOT_COMPILE_LIBRARY`,在使用动态库时定义宏:`QCUSTOMPLOT_USE_LIBRARY`
7 |
8 | 下载地址:https://www.qcustomplot.com/index.php/download
9 |
10 | ## 二、简单介绍QCustomPlot的几个重要类
11 |
12 | * QCustomPlot 图表类:用于图表的显示和交互
13 | * QCPLayer 图层:管理图层元素(QCPLayerable),所有可显示的对象都是继承自图层元素
14 | * QCPAbstractPlottable 绘图元素:包含 折线图(QCPGraph)、曲线图(QCPCurve)、柱状图(QCPBars)、QCPStatiBox(盒子图)、QCPColorMap(色谱图)、QCPFinancial(金融图)
15 | * QCPAxisRect 坐标轴矩形:一个坐标轴矩形默认包含上下左右四个坐标轴,但是可以添加多个坐标轴
16 |
17 | ## 三、简单介绍QCustomPlot类
18 |
19 | QCustomPlot类管理着所有的图层,它默认自带了六个图层,分别是:
20 |
21 | 1. 背景层`background`
22 | 2. 网格层`grid`
23 | 3. 绘图层`main`
24 | 4. 坐标轴层`axes`
25 | 5. 图例层`legend`
26 | 6. overlay层`overlay`
27 |
28 | 依据层的顺序的不同,绘制的顺序也不同,越在底下的层越早绘制,当前层默认为绘图层`main`
29 |
30 | 而我们的绘图区域则在QCPAxisRect中,QCustomPlot类默认包含一个QCPAxisRect,我们可以在下图中可以看到一个QCPAxisRect一般来说会有上轴`xAxis2`、下轴`xAxis`、左轴`yAxis`和右轴`yAxis2`四个轴
31 |
32 | 
33 |
34 |
35 |
36 | ## 四、简单使用
37 |
38 | 我们以官方的一个简单示例来结束这篇
39 | ```
40 | void MainWindow::setupQuadraticDemo(QCustomPlot *customPlot)
41 | {
42 | QVector x(101), y(101);
43 | for (int i = 0; i < 101; ++i) {
44 | x[i] = i / 50.0 - 1; // -1 到 1
45 | y[i] = x[i] * x[i];
46 | }
47 |
48 | customPlot->addGraph(); // 添加一个曲线图QGraph
49 | customPlot->graph(0)->setData(x, y); // 为曲线图添加数据
50 | customPlot->graph(0)->setName("第一个示例"); // 设置曲线图的名字
51 | customPlot->xAxis->setLabel("x"); // 设置x轴的标签
52 | customPlot->yAxis->setLabel("y");
53 | customPlot->xAxis->setRange(-1, 1); // 设置x轴的范围为(-1,1)
54 | customPlot->yAxis->setRange(0, 1);
55 | customPlot->legend->setVisible(true); // 显示图例
56 | }
57 | ```
58 |
59 | 效果图
60 |
61 | 
62 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之柱状图(三).md:
--------------------------------------------------------------------------------
1 | 在QCustomPlot中,柱状图需要使用QCPBars类, QCPBars的使用很简单
2 |
3 | #### 竖向柱状图
4 | 创建一个柱状图,并且设置它的风格
5 | ```
6 | QCPAxis *keyAxis = customPlot->xAxis;
7 | QCPAxis *valueAxis = customPlot->yAxis;
8 | QCPBars *fossil = new QCPBars(keyAxis, valueAxis); // 使用xAxis作为柱状图的key轴,yAxis作为value轴
9 |
10 | fossil->setAntialiased(false); // 为了更好的边框效果,关闭抗齿锯
11 | fossil->setName("Fossil fuels"); // 设置柱状图的名字,可在图例中显示
12 | fossil->setPen(QPen(QColor(0, 168, 140).lighter(130))); // 设置柱状图的边框颜色
13 | fossil->setBrush(QColor(0, 168, 140)); // 设置柱状图的画刷颜色
14 | ```
15 |
16 | 之后,我们为柱状图的key轴设置一个文字类型的轴
17 | ```
18 | // 为柱状图设置一个文字类型的key轴,ticks决定了轴的范围,而labels决定了轴的刻度文字的显示
19 | QVector ticks;
20 | QVector labels;
21 | ticks << 1 << 2 << 3 << 4 << 5 << 6 << 7;
22 | labels << "USA" << "Japan" << "Germany" << "France" << "UK" << "Italy" << "Canada";
23 | QSharedPointer textTicker(new QCPAxisTickerText);
24 | textTicker->addTicks(ticks, labels);
25 |
26 | keyAxis->setTicker(textTicker); // 设置为文字轴
27 | ```
28 |
29 | 设置柱状图轴范围,并且为其添加数据数据
30 | ```
31 | keyAxis->setTickLabelRotation(60); // 轴刻度文字旋转60度
32 | keyAxis->setSubTicks(false); // 不显示子刻度
33 | keyAxis->setTickLength(0, 4); // 轴内外刻度的长度分别是0,4,也就是轴内的刻度线不显示
34 | keyAxis->setRange(0, 8); // 设置范围
35 | keyAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
36 |
37 | valueAxis->setRange(0, 12.1);
38 | valueAxis->setPadding(35); // 轴的内边距,可以到QCustomPlot之开始(一)看图解
39 | valueAxis->setLabel("Power Consumption in\nKilowatts per Capita (2007)");
40 | valueAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
41 | QVector fossilData;
42 | fossilData << 0.86*10.5 << 0.83*5.5 << 0.84*5.5 << 0.52*5.8 << 0.89*5.2 << 0.90*4.2 << 0.67*11.2;
43 | fossil->setData(ticks, fossilData);
44 | ```
45 | 
46 |
47 | #### 横向柱状图
48 |
49 | 横向柱状图也很简单,只要设置key轴为y轴,value轴为x轴即可
50 | ```
51 | QCPAxis *keyAxis = customPlot->yAxis;
52 | QCPAxis *valueAxis = customPlot->xAxis;
53 | ```
54 |
55 | 
56 |
57 | #### 柱状堆积图
58 | 为了展示堆积图,我们再添加了两个柱状图
59 | ```
60 | QCPBars *regen = new QCPBars(keyAxis, valueAxis);
61 | QCPBars *nuclear = new QCPBars(keyAxis, valueAxis);
62 | QCPBars *fossil = new QCPBars(keyAxis, valueAxis); // 使用xAxis作为柱状图的key轴,yAxis作为value轴
63 | ```
64 |
65 | 设置它们的数据
66 | ```
67 | QVector fossilData, nuclearData, regenData;
68 | fossilData << 0.86*10.5 << 0.83*5.5 << 0.84*5.5 << 0.52*5.8 << 0.89*5.2 << 0.90*4.2 << 0.67*11.2;
69 | nuclearData << 0.08*10.5 << 0.12*5.5 << 0.12*5.5 << 0.40*5.8 << 0.09*5.2 << 0.00*4.2 << 0.07*11.2;
70 | regenData << 0.06*10.5 << 0.05*5.5 << 0.04*5.5 << 0.06*5.8 << 0.02*5.2 << 0.07*4.2 << 0.25*11.2;
71 | fossil->setData(ticks, fossilData);
72 | nuclear->setData(ticks, nuclearData);
73 | regen->setData(ticks, regenData);
74 | ```
75 |
76 | 接下来设置堆积方式
77 | ```
78 | regen->setStackingGap(1); // 设置堆积在其它柱状图上时的间距(像素)
79 | nuclear->setStackingGap(1);
80 |
81 | nuclear->moveAbove(fossil); // 将nuclear移到fossil之上
82 | regen->moveAbove(nuclear);
83 | ```
84 |
85 | 
86 |
87 | #### 柱状分组图
88 | 柱状分组图需要引入一个新的类:`QCPBarsGroup`,首先注释掉上面的`堆积方式`的代码
89 |
90 | ```
91 | QCPBarsGroup *group = new QCPBarsGroup(customPlot);
92 |
93 | QList bars;
94 | bars << fossil << nuclear << regen;
95 |
96 | foreach (QCPBars *bar, bars) {
97 | // 设置柱状图的宽度类型为以key坐标轴计算宽度的大小,其实默认就是这种方式
98 | bar->setWidthType(QCPBars::wtPlotCoords);
99 | bar->setWidth(bar->width() / bars.size()); // 设置柱状图的宽度大小
100 | group->append(bar); // 将柱状图加入柱状图分组中
101 | }
102 |
103 | group->setSpacingType(QCPBarsGroup::stAbsolute); // 设置组内柱状图的间距,按像素
104 | group->setSpacing(2); // 设置较小的间距值,这样看起来更紧凑
105 | ```
106 |
107 | 
108 |
109 | #### 柱状图宽度类型和柱状分组图间距类型
110 |
111 | 柱状图有三种宽度类型,分别是:
112 |
113 | * QCPBars::wtAbsolute 宽度是绝对像素大小,即setWidth设置为多少就是多少
114 | * QCPBars::wtAxisRectRatio 宽度大小是以QCPAxisRect的大小决定的,当key轴为水平的时候,宽度大小为setWidth设置的比例值乘以QCPAxisRect的宽度;key轴为垂直的时候,是乘以QCPAxisRect的高度
115 | * QCPBars::wtPlotCoords 宽度大小是以key坐标轴刻度位置以及setWidth设置的值确定,宽度的计算方式为当前key±width
116 |
117 | 柱状分组图的间距类型和柱状图的宽度类型是类似的
118 |
119 | #### 在柱状图上显示值
120 | 有时候我们需要在柱状图上显示具体的值,这时我们仅需继承`QCPBars`
121 |
122 | ```
123 | // 头文件CustomBars.h
124 | class CustomBars : public QCPBars
125 | {
126 | public:
127 | explicit CustomBars(QCPAxis *keyAxis, QCPAxis *valueAxis);
128 |
129 | Qt::Alignment textAligment() const { return mTextAlignment; }
130 | double spacing() const { return mSpacing; }
131 | QFont font() const { return mFont; }
132 |
133 | void setTextAlignment(Qt::Alignment alignment);
134 | void setSpacing(double spacing);
135 | void setFont(const QFont &font);
136 |
137 | protected:
138 | Qt::Alignment mTextAlignment; // 文字对齐方式
139 | double mSpacing; // 文字与柱状图的间距,这里按像素大小
140 | QFont mFont; // 文字使用的字体
141 |
142 | virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
143 | };
144 | ```
145 |
146 | ```
147 | // 源文件CustomBars.cpp
148 | CustomBars::CustomBars(QCPAxis *keyAxis, QCPAxis *valueAxis)
149 | : QCPBars (keyAxis, valueAxis),
150 | mTextAlignment(Qt::AlignCenter),
151 | mSpacing(5),
152 | mFont(QFont(QLatin1String("sans serif"), 12))
153 | {
154 |
155 | }
156 |
157 | void CustomBars::setTextAlignment(Qt::Alignment alignment)
158 | {
159 | mTextAlignment = alignment;
160 | }
161 |
162 | void CustomBars::setSpacing(double spacing)
163 | {
164 | mSpacing = spacing;
165 | }
166 |
167 | void CustomBars::setFont(const QFont &font)
168 | {
169 | mFont = font;
170 | }
171 | ```
172 |
173 | **draw函数的绘制** 我们直接拷贝QCPBars的draw函数源码过来,在其上面修改即可
174 | ```
175 | // 源文件CustomBars.cpp
176 | void CustomBars::draw(QCPPainter *painter)
177 | {
178 |
179 | // 以上是拷贝的源码部分
180 | painter->drawPolygon(barRect);
181 |
182 | // 我们仅需在 painter->drawPolygon(barRect); 这行下增加以下的内容即可
183 |
184 | // 计算文字的位置
185 | painter->setFont(mFont); // 设置字体
186 | QString text = QString text = QString::number(it->value, 'g', 2); // 取得当前value轴的值,保留两位精度
187 |
188 | QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, text); // 计算文字所占用的大小
189 |
190 | if (mKeyAxis.data()->orientation() == Qt::Horizontal) { // 当key轴为水平轴的时候
191 | if (mKeyAxis.data()->axisType() == QCPAxis::atTop) // 上轴,移动文字到柱状图下面
192 | textRect.moveTopLeft(barRect.bottomLeft() + QPointF(0, mSpacing));
193 | else // 下轴,移动文字到柱状图上面
194 | textRect.moveBottomLeft(barRect.topLeft() - QPointF(0, mSpacing));
195 | textRect.setWidth(barRect.width());
196 | painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);
197 | } else { // 当key轴为竖直轴的时候
198 | if (mKeyAxis.data()->axisType() == QCPAxis::atLeft) // 左轴,移动文字到柱状图右边
199 | textRect.moveTopLeft(barRect.topRight() + QPointF(mSpacing, 0));
200 | else // 右轴,移动文字到柱状图左边
201 | textRect.moveTopRight(barRect.topLeft() - QPointF(mSpacing, 0));
202 | textRect.setHeight(barRect.height());
203 | painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);
204 | }
205 |
206 | // 以下是拷贝的源码部分
207 | }
208 | ```
209 |
210 | 使用很简单,仅需将`QCPBars`替换成`CustomBars`
211 | ```
212 | CustomBars *regen = new CustomBars(keyAxis, valueAxis);
213 | CustomBars *nuclear = new CustomBars(keyAxis, valueAxis);
214 | CustomBars *fossil = new CustomBars(keyAxis, valueAxis); // 使用xAxis作为柱状图的key轴,yAxis作为value轴
215 | ```
216 |
217 | 
218 |
219 | #### 最后补充一点
220 | 我们可以通过`setBaseValue`函数设置柱状图的起点位置,这个函数仅对最底下的柱状图有效果(即其没有堆积在别的柱状图之上)
221 | ```
222 | foreach (QCPBars *bar, bars) {
223 | // 设置柱状图的宽度类型为以key坐标轴计算宽度的大小,其实默认就是这种方式
224 | bar->setBaseValue(2.5); // 设置柱状图的起点为value轴值为2.5的位置
225 | }
226 | ```
227 |
228 | 
229 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之简单动态图(六).md:
--------------------------------------------------------------------------------
1 | 本章节是仿照echart的动态图:[地址](https://www.echartsjs.com/examples/zh/editor.html?c=dynamic-data)
2 |
3 | 
4 |
5 | #### 一、设置布局
6 |
7 | 首先新增一行一列用于放置标题和图例,这里将图例放置在一个空的轴矩形当中--[QCustomPlot之层和布局(四)](https://www.jianshu.com/p/4c4c0e2d01e8)
8 |
9 |
10 | ```
11 | // setupDynamicData(QCustomPlot *customPlot) 函数中
12 | customPlot->plotLayout()->insertRow(0);
13 | customPlot->plotLayout()->insertColumn(0);
14 |
15 | QCPAxisRect *legendRect = new QCPAxisRect(customPlot, false); // 不需要配置轴,因为我们只是把图例放在这里
16 | legendRect->setAutoMargins(QCP::msNone); // 不计算边距
17 | legendRect->insetLayout()->addElement(customPlot->legend, Qt::AlignCenter); // 放置图例
18 | customPlot->legend->setVisible(true);
19 | customPlot->legend->setFillOrder(QCPLayoutGrid::foColumnsFirst); // 横向图例
20 |
21 | customPlot->axisRect()->setAutoMargins(QCP::msBottom | QCP::msRight); // 只计算下边距和右边距
22 | customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, "动态数据", QFont("sans", 12, QFont::Bold)));
23 | customPlot->plotLayout()->addElement(0, 1, legendRect);
24 | customPlot->plotLayout()->setRowStretchFactor(0, 0.1); // 让其尽可能小一点
25 | customPlot->plotLayout()->setColumnStretchFactor(0, 0.1);
26 | ```
27 |
28 | #### 二、设置图表
29 |
30 | 其次添加一个柱状图和折线图,并且添加它们的数据,注意这里采用`QCPAxisTickerText`而不采用`QCPAxisTickerTime`或者`QCPAxisTickerDateTime`的原因,是因为我们不想要它们计算刻度线的位置,同时要注意让`xAxis2`保持与`xAxis`的联动,这里只需连接信号槽即可
31 |
32 | ```
33 | // setupDynamicData(QCustomPlot *customPlot) 函数中
34 | // 设置柱状图
35 | QCPBars *bar = new QCPBars(customPlot->xAxis, customPlot->yAxis2);
36 | bar->setName("预购队列");
37 | bar->setPen(Qt::NoPen);
38 | bar->setBrush(QColor(194, 53, 49));
39 |
40 | // 设置折线图
41 | QCPGraph *graph = customPlot->addGraph(customPlot->xAxis, customPlot->yAxis);
42 | graph->setName("最新成交价");
43 | graph->setPen(QPen(QColor(47, 69, 84), 2));
44 | graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor(47, 69, 84), QColor(Qt::white), 4));
45 |
46 | customPlot->yAxis->setLabel("价格");
47 | customPlot->yAxis->setRange(0, 30);
48 | customPlot->yAxis->setSubTicks(false); // 设置子刻度线不显示
49 | customPlot->yAxis->setTickLength(0, 6); // 设置刻度线内外的长度
50 | customPlot->yAxis2->setLabel("预购量");
51 | customPlot->yAxis2->setVisible(true);
52 | customPlot->yAxis2->setRange(0, 1200);
53 | customPlot->yAxis2->setSubTicks(false);
54 | customPlot->yAxis2->setTickLength(0, 6);
55 |
56 | // 这里之所以用 QCPAxisTickerText,而不用 QCPAxisTickerTime / QCPAxisTickerDateTime 是因为它们会自动计算刻度线的位置,这是我们不想要的
57 | QSharedPointer timeTicker(new QCPAxisTickerText);
58 | QSharedPointer indexTicker(new QCPAxisTickerText);
59 | customPlot->xAxis->setTicker(timeTicker);
60 | customPlot->xAxis->setSubTicks(false);
61 | customPlot->xAxis2->setVisible(true);
62 | customPlot->xAxis2->setSubTicks(false);
63 | customPlot->xAxis2->setTicker(indexTicker);
64 | connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange))); // 重要:让xAxis2与xAxis保持联动
65 |
66 | // 添加数据
67 | QVector datax, datay1, datay2;
68 | QTime now = QTime::currentTime();
69 | for (int i = 0; i < 8; ++i) {
70 | mLabels.insert(0, now.toString("hh:mm:ss")); // mLabels == QVector
71 | datax.insert(0, now.msecsSinceStartOfDay() / 1000.0); // 时间
72 | now = now.addMSecs(-2000);
73 |
74 | mIndexLabels.insert(0, QString::number(8 - i));
75 | datay1.insert(0, QRandomGenerator::global()->bounded(20) + 5); // 产生随机数,Qt 5.10 以下用qrand() % 20
76 | datay2.insert(0, QRandomGenerator::global()->bounded(1000));
77 | }
78 |
79 | mIndex = 8;
80 | mPositions = datax; // mPositions == QVector
81 |
82 | graph->setData(datax, datay1);
83 | bar->setData(datax, datay2);
84 |
85 | timeTicker->setTicks(mPositions, mLabels); // 设置刻度线位置和刻度标签
86 | indexTicker->setTicks(mPositions, mIndexLabels);
87 |
88 | customPlot->xAxis->rescale();
89 | customPlot->xAxis->scaleRange(1.1); // 稍微缩放一下,以显示全部
90 | ```
91 |
92 | #### 三、连接计时信号槽
93 | ```
94 | // setupDynamicData(QCustomPlot *customPlot) 函数中
95 | connect(&dataTimer, SIGNAL(timeout()), this, SLOT(dynamicDataSlot()));
96 | dataTimer.start(2000); // 2秒刷新一次
97 | ```
98 |
99 | #### 四、设置数据刷新的槽函数
100 |
101 | 以下都是在`dynamicDataSlot`槽函数中
102 |
103 | - 去除之前的数据
104 |
105 | ```
106 | QCPBars *bar = static_cast(ui->customPlot->plottable(0));
107 |
108 | // 移除第一个数据
109 | bar->data()->remove(mPositions.first());
110 | ui->customPlot->graph(0)->data()->remove(mPositions.first());
111 |
112 | mPositions.removeFirst();
113 | mLabels.removeFirst();
114 | mIndexLabels.removeFirst();
115 | ```
116 |
117 | - 添加新增数据
118 |
119 | ```
120 | // 计算当前时间
121 | double key = QTime::currentTime().msecsSinceStartOfDay() / 1000.0;
122 | QString label = QTime::currentTime().toString("hh:mm:ss");
123 |
124 | ui->customPlot->graph(0)->addData(key, QRandomGenerator::global()->bounded(20) + 5);
125 | bar->addData(key, QRandomGenerator::global()->bounded(1000));
126 |
127 | mPositions.push_back(key);
128 | mLabels.push_back(label);
129 | mIndexLabels.push_back(QString::number(++mIndex));
130 | ```
131 |
132 | - 重新设置轴并刷新图表
133 |
134 | ```
135 | QCPAxisTickerText *timeTicker = static_cast(ui->customPlot->xAxis->ticker().data());
136 | timeTicker->setTicks(mPositions, mLabels); // 重新设置x轴
137 |
138 | QCPAxisTickerText *indexTicker = static_cast(ui->customPlot->xAxis2->ticker().data());
139 | indexTicker->setTicks(mPositions, mIndexLabels);
140 |
141 | ui->customPlot->xAxis->rescale();
142 | ui->customPlot->xAxis->scaleRange(1.1);
143 |
144 | ui->customPlot->replot();
145 | ```
146 |
147 |
--------------------------------------------------------------------------------
/docs/zh-cn/QCustomPlot之轴矩形和轴(五).md:
--------------------------------------------------------------------------------
1 | #### 轴矩形QCPAxisRect
2 |
3 | 轴矩形的作用主要有以下几种:
4 |
5 | - 背景绘制,所以轴矩形默认存在于`background`层
6 | - 管理多个轴,并不仅限于上下左右四个轴
7 | - 图表的拖拽和缩放
8 |
9 | 先来看下轴矩形的构造函数,可以看到,轴矩形管理着上下左右四个方向的轴,同时当`setupDefaultAxes`为true时(默认为true)时,将会添加上下左右四个轴,并且设置下轴(x轴)和左轴(y轴)为拖拽和缩放时影响的轴
10 |
11 | ```
12 | QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes)
13 | : QCPLayoutElement(parentPlot),
14 | mBackgroundBrush(Qt::NoBrush),
15 | mBackgroundScaled(true),
16 | mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
17 | mInsetLayout(new QCPLayoutInset),
18 | mRangeDrag(Qt::Horizontal | Qt::Vertical), // 水平和竖直方向都可以拖拽
19 | mRangeZoom(Qt::Horizontal | Qt::Vertical), // 水平和竖直方向都可以缩放
20 | mRangeZoomFactorHorz(0.85), // 水平缩放比例
21 | mRangeZoomFactorVert(0.85), // 竖直缩放比例
22 | mDragging(false)
23 | {
24 | // 其余无关代码
25 |
26 | mAxes.insert(QCPAxis::atLeft, QList());
27 | mAxes.insert(QCPAxis::atRight, QList());
28 | mAxes.insert(QCPAxis::atTop, QList());
29 | mAxes.insert(QCPAxis::atBottom, QList());
30 |
31 | if (setupDefaultAxes) {
32 | QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
33 | QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
34 | QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
35 | QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
36 | setRangeDragAxes(xAxis, yAxis); // 设置拖拽时影响的轴
37 | setRangeZoomAxes(xAxis, yAxis); // 设置缩放时影响的轴
38 |
39 | // 其余无关代码
40 | }
41 | }
42 | ```
43 |
44 |
45 | 于是我们可以知道,轴矩形是怎么影响图表的拖拽和缩放的:
46 | 1. mRangeDrag、mRangeZoom作用的方向,由setRangeDrag和setRangeZoom函数设置
47 | 2. setRangeDragAxes和setRangeZoomAxes函数设置的拖拽和缩放时影响的轴(可以是多个轴)
48 |
49 |
50 | 同时轴矩形还提供了函数zoom函数,可以很方便的实现矩形框选缩放的功能
51 |
52 | #### 轴QCPAxis
53 |
54 | 轴的作用主要是:决定图表的范围
55 |
56 | 轴主要由四部分组成:
57 | - 轴线及刻度线
58 | - 轴刻度文字
59 | - 轴标签
60 | - 网格线
61 |
62 | QCPAxis可以为多个图表所共有,同时它提供了非常丰富的接口用于设置上述组成部分的风格,[QCustomPlot之个性化外观(二)](https://www.jianshu.com/p/bdd8b363e6b7)的内容
63 |
64 | QCustomPlot还为我们提供了几种默认的轴(ticker, 其实是用于产生刻度和刻度文字的):
65 | - QCPAxisTickerFixed // 固定步进的轴
66 | - QCPAxisTickerLog // log轴
67 | - QCPAxisTickerPi // Pi轴
68 | - QCPAxisTickerText // 文字轴
69 | - QCPAxisTickerDateTime // 日期轴
70 | - QCPAxisTickerTime // 时间轴
71 |
72 | 使用**setTicker**函数设置相应的ticker就可以了
73 |
74 | 
75 |
76 | **setNumberFormat**函数的介绍:用于轴标签文字的显示格式,可以由以下三个字符组成
77 | - 第一个字符可以为:'e'/'E'、'g'/'G'、'f',这里使用了Qt的显示风格
78 | - 第二个字符必须为:'b',当且仅当第一个字符为'e'(科学计数法)或者'g'(精度为最大有效位数)时才有效,b即beautiful,可以让轴刻度文字看起来更好看
79 | - 第三个字符可以为:'c'(cross)、'd'(dot),即表现为乘号或者点
80 |
81 |
82 | #### 总结
83 | - 轴矩形可以拥有多个轴
84 | - 多个图表可以共用一个轴
85 | - QCustomPlot可以存在多个轴矩形,因为轴矩形继承自`QCPLayoutElement`
86 |
87 |
88 | ```
89 | void MainWindow::setupAdvancedAxesDemo(QCustomPlot *customPlot)
90 | {
91 | demoName = "Advanced Axes Demo";
92 |
93 | customPlot->plotLayout()->clear(); // 首先清空默认的轴矩形,让我们从头开始
94 | QCPAxisRect *wideAxisRect = new QCPAxisRect(customPlot, true); // 还记得setupDefaultAxes为true时的作用吗,忘了的话翻上去看吧
95 | wideAxisRect->setupFullAxesBox(true); // 让四个轴关联,并全部显示出来
96 | wideAxisRect->addAxis(QCPAxis::atLeft)->setTickLabelColor(QColor("#6050F8")); // 在左边多添加一个轴并且设置它的颜色
97 |
98 | QCPLayoutGrid *subLayout = new QCPLayoutGrid;
99 | customPlot->plotLayout()->addElement(0, 0, wideAxisRect); // 在第一行添加轴矩形
100 | customPlot->plotLayout()->addElement(1, 0, subLayout); // 在第二行添加一个子布局,后面会添加两个轴矩形在里面
101 |
102 | QCPAxisRect *subRectLeft = new QCPAxisRect(customPlot, false); // 不配置轴
103 | QCPAxisRect *subRectRight = new QCPAxisRect(customPlot, false);
104 |
105 | // 让右边的轴矩形固定大小
106 | subRectRight->setMaximumSize(100, 100);
107 | subRectRight->setMinimumSize(100, 100);
108 |
109 | subLayout->addElement(0, 0, subRectLeft); // 在第一列添加轴矩形
110 | subLayout->addElement(0, 1, subRectRight); // 在第二列添加轴矩形
111 |
112 | subRectLeft->addAxes(QCPAxis::atBottom | QCPAxis::atLeft); // 添加下轴和左轴
113 | subRectRight->addAxes(QCPAxis::atBottom | QCPAxis::atRight); // 添加下轴和右轴
114 | subRectLeft->axis(QCPAxis::atLeft)->ticker()->setTickCount(2); // 设置轴的刻度为一个固定的步进值
115 | subRectRight->axis(QCPAxis::atRight)->ticker()->setTickCount(2);
116 | subRectLeft->axis(QCPAxis::atBottom)->grid()->setVisible(true);
117 |
118 | // 保持一个好的习惯,将它们放置在相应的层
119 | foreach (auto *rect, customPlot->axisRects()) {
120 | foreach (auto *axis, rect->axes()) {
121 | axis->setLayer("axes");
122 | axis->grid()->setLayer("grid");
123 | }
124 | }
125 |
126 | // 准备数据
127 | QVector dataCos(21), dataGauss(50), dataRandom(100);
128 | QVector x3, y3;
129 | qsrand(3);
130 | for (int i=0; iaddGraph(wideAxisRect->axis(QCPAxis::atBottom), wideAxisRect->axis(QCPAxis::atLeft));
147 | mainGraphCos->data()->set(dataCos);
148 | mainGraphCos->valueAxis()->setRange(-1, 1);
149 | mainGraphCos->rescaleKeyAxis();
150 | mainGraphCos->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black), QBrush(Qt::white), 6));
151 | mainGraphCos->setPen(QPen(QColor(120, 120, 120), 2));
152 |
153 | QCPGraph *mainGraphGauss = customPlot->addGraph(wideAxisRect->axis(QCPAxis::atBottom), wideAxisRect->axis(QCPAxis::atLeft, 1));
154 | mainGraphGauss->data()->set(dataGauss);
155 | mainGraphGauss->setPen(QPen(QColor("#8070B8"), 2));
156 | mainGraphGauss->setBrush(QColor(110, 170, 110, 30));
157 | mainGraphCos->setChannelFillGraph(mainGraphGauss);
158 | mainGraphCos->setBrush(QColor(255, 161, 0, 50));
159 | mainGraphGauss->valueAxis()->setRange(0, 1000);
160 | mainGraphGauss->rescaleKeyAxis();
161 |
162 | QCPGraph *subGraphRandom = customPlot->addGraph(subRectLeft->axis(QCPAxis::atBottom), subRectLeft->axis(QCPAxis::atLeft));
163 | subGraphRandom->data()->set(dataRandom);
164 | subGraphRandom->setLineStyle(QCPGraph::lsImpulse);
165 | subGraphRandom->setPen(QPen(QColor("#FFA100"), 1.5));
166 | subGraphRandom->rescaleAxes();
167 |
168 | QCPBars *subBars = new QCPBars(subRectRight->axis(QCPAxis::atBottom), subRectRight->axis(QCPAxis::atRight));
169 | subBars->setWidth(3/(double)x3.size());
170 | subBars->setData(x3, y3);
171 | subBars->setPen(QPen(Qt::black));
172 | subBars->setAntialiased(false);
173 | subBars->setAntialiasedFill(false);
174 | subBars->setBrush(QColor("#705BE8"));
175 | subBars->keyAxis()->setSubTicks(false);
176 | subBars->rescaleAxes();
177 |
178 | // 给柱状图一个固定步进轴
179 | QSharedPointer intTicker(new QCPAxisTickerFixed);
180 | intTicker->setTickStep(1.0);
181 | intTicker->setScaleStrategy(QCPAxisTickerFixed::ssMultiples);
182 | subBars->keyAxis()->setTicker(intTicker);
183 | }
184 | ```
185 |
186 | 
187 |
--------------------------------------------------------------------------------
/src/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.5)
2 | project(qcustomplot-manual)
3 |
4 | set(ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/..)
5 | set(EXECUTABLE_OUTPUT_PATH ${ROOT_PATH}/bin)
6 | set(LIBRARY_OUTPUT_PATH ${ROOT_PATH}/bin)
7 |
8 | add_subdirectory(qcustomplot)
9 | add_subdirectory(examples)
10 |
--------------------------------------------------------------------------------
/src/examples/001_start/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/001_start/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/001_start/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 | #include "qcustomplot.h"
3 |
4 | MainWindow::MainWindow(QWidget *parent)
5 | : QMainWindow(parent)
6 | {
7 | QCustomPlot* customPlot = new QCustomPlot;
8 | setCentralWidget(customPlot);
9 |
10 | setupQuadraticDemo(customPlot);
11 | }
12 |
13 | void MainWindow::setupQuadraticDemo(QCustomPlot *customPlot)
14 | {
15 | QVector x(101), y(101);
16 | for (int i = 0; i < 101; ++i) {
17 | x[i] = i / 50.0 - 1; // -1 到 1
18 | y[i] = x[i] * x[i];
19 | }
20 |
21 | customPlot->addGraph(); // 添加一个曲线图QGraph
22 | customPlot->graph(0)->setData(x, y); // 为曲线图添加数据
23 | customPlot->graph(0)->setName(QString::fromLocal8Bit("第一个示例")); // 设置曲线图的名字
24 | customPlot->xAxis->setLabel("x"); // 设置x轴的标签
25 | customPlot->yAxis->setLabel("y");
26 | customPlot->xAxis->setRange(-1, 1); // 设置x轴的范围为(-1,1)
27 | customPlot->yAxis->setRange(0, 1);
28 | customPlot->legend->setVisible(true); // 显示图例
29 | }
30 |
--------------------------------------------------------------------------------
/src/examples/001_start/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 |
6 | class QCustomPlot;
7 |
8 | class MainWindow : public QMainWindow
9 | {
10 | public:
11 | MainWindow(QWidget* parent = nullptr);
12 |
13 | void setupQuadraticDemo(QCustomPlot *customPlot);
14 |
15 | private:
16 |
17 | };
18 |
19 | #endif // MAINWINDOW_H
20 |
--------------------------------------------------------------------------------
/src/examples/003_bar_chart_demo/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/003_bar_chart_demo/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/003_bar_chart_demo/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 |
3 | #include
4 | #include
5 |
6 | #include "qcustomplot.h"
7 | #include "qcptextbars.h"
8 |
9 | MainWindow::MainWindow(QWidget *parent)
10 | : QMainWindow(parent)
11 | {
12 | mCustomPlot = new QCustomPlot;
13 |
14 | setWindowTitle("QCustomPlot: Bar Chart Demo");
15 |
16 | QWidget* w = new QWidget;
17 | QVBoxLayout* layout = new QVBoxLayout;
18 | w->setLayout(layout);
19 | setCentralWidget(w);
20 |
21 | QStringList items;
22 | items << QString::fromLocal8Bit("竖向柱状图")
23 | << QString::fromLocal8Bit("横向柱状图")
24 | << QString::fromLocal8Bit("竖向堆积图")
25 | << QString::fromLocal8Bit("横向堆积图")
26 | << QString::fromLocal8Bit("竖向分组图")
27 | << QString::fromLocal8Bit("横向分组图")
28 | << QString::fromLocal8Bit("竖向文字显示")
29 | << QString::fromLocal8Bit("横向文字显示");
30 |
31 | QComboBox* comboBox = new QComboBox;
32 | comboBox->addItems(items);
33 | connect(comboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::setupDemo);
34 |
35 | layout->addWidget(comboBox);
36 | layout->addWidget(mCustomPlot);
37 | setupDemo(0);
38 | }
39 |
40 | void MainWindow::reset()
41 | {
42 | delete mCustomPlot;
43 | mCustomPlot = new QCustomPlot;
44 | centralWidget()->layout()->addWidget(mCustomPlot);
45 |
46 | mOrientation = Qt::Vertical;
47 | mIsStackedBar = false;
48 | mIsGroupBar = false;
49 | mTextVisible = false;
50 | }
51 |
52 | void MainWindow::setupDemo(int index)
53 | {
54 | reset();
55 |
56 | switch (index) {
57 | case 0: mOrientation = Qt::Vertical; setupBarDemo(mCustomPlot); break;
58 | case 1: mOrientation = Qt::Horizontal; setupBarDemo(mCustomPlot); break;
59 | case 2: mOrientation = Qt::Vertical; mIsStackedBar = true; setupBarDemo(mCustomPlot); break;
60 | case 3: mOrientation = Qt::Horizontal; mIsStackedBar = true; setupBarDemo(mCustomPlot); break;
61 | case 4: mOrientation = Qt::Vertical; mIsGroupBar = true; setupBarDemo(mCustomPlot); break;
62 | case 5: mOrientation = Qt::Horizontal; mIsGroupBar = true; setupBarDemo(mCustomPlot); break;
63 | case 6: mOrientation = Qt::Vertical; mTextVisible = true; mIsGroupBar = true; setupBarDemo(mCustomPlot); break;
64 | case 7: mOrientation = Qt::Horizontal; mTextVisible = true; mIsGroupBar = true; setupBarDemo(mCustomPlot); break;
65 | }
66 | }
67 |
68 | void MainWindow::setupBarDemo(QCustomPlot *customPlot)
69 | {
70 | QCPAxis *keyAxis = customPlot->xAxis;
71 | QCPAxis *valueAxis = customPlot->yAxis;
72 |
73 | // 水平方向
74 | if (mOrientation == Qt::Horizontal) {
75 | keyAxis = customPlot->yAxis;
76 | valueAxis = customPlot->xAxis;
77 | }
78 |
79 | auto *regen = new QCPTextBars(keyAxis, valueAxis);
80 | auto *nuclear = new QCPTextBars(keyAxis, valueAxis);
81 | auto *fossil = new QCPTextBars(keyAxis, valueAxis); // 使用xAxis作为柱状图的key轴,yAxis作为value轴
82 | regen->setTextVisible(mTextVisible);
83 | nuclear->setTextVisible(mTextVisible);
84 | fossil->setTextVisible(mTextVisible);
85 |
86 | regen->setAntialiased(false); // 为了更好的边框效果,关闭抗齿锯
87 | nuclear->setAntialiased(false); // 为了更好的边框效果,关闭抗齿锯
88 | fossil->setAntialiased(false); // 为了更好的边框效果,关闭抗齿锯
89 |
90 | regen->setName("Regenerative");
91 | regen->setPen(QPen(QColor(111, 9, 176).lighter(170)));
92 | regen->setBrush(QColor(111, 9, 176));
93 | nuclear->setName("Nuclear");
94 | nuclear->setPen(QPen(QColor(250, 170, 20).lighter(150)));
95 | nuclear->setBrush(QColor(250, 170, 20));
96 |
97 | fossil->setName("Fossil fuels"); // 设置柱状图的名字,可在图例中显示
98 | fossil->setPen(QPen(QColor(0, 168, 140).lighter(130))); // 设置柱状图的边框颜色
99 | fossil->setBrush(QColor(0, 168, 140)); // 设置柱状图的画刷颜色
100 |
101 | // 为柱状图设置一个文字类型的key轴,ticks决定了轴的范围,而labels决定了轴的刻度文字的显示
102 | QVector ticks;
103 | QVector labels;
104 | ticks << 1 << 2 << 3 << 4 << 5 << 6 << 7;
105 | labels << "USA" << "Japan" << "Germany" << "France" << "UK" << "Italy" << "Canada";
106 | QSharedPointer textTicker(new QCPAxisTickerText);
107 | textTicker->addTicks(ticks, labels);
108 |
109 | keyAxis->setTicker(textTicker); // 设置为文字轴
110 |
111 | keyAxis->setTickLabelRotation(60); // 轴刻度文字旋转60度
112 | keyAxis->setSubTicks(false); // 不显示子刻度
113 | keyAxis->setTickLength(0, 4); // 轴内外刻度的长度分别是0,4,也就是轴内的刻度线不显示
114 | keyAxis->setRange(0, 8); // 设置范围
115 | keyAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
116 |
117 | valueAxis->setRange(0, 12.1);
118 | valueAxis->setPadding(35); // 轴的内边距,可以到QCustomPlot之开始(一)看图解
119 | valueAxis->setLabel("Power Consumption in\nKilowatts per Capita (2007)");
120 | valueAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
121 | QVector fossilData, nuclearData, regenData;
122 | fossilData << 0.86*10.5 << 0.83*5.5 << 0.84*5.5 << 0.52*5.8 << 0.89*5.2 << 0.90*4.2 << 0.67*11.2;
123 | nuclearData << 0.08*10.5 << 0.12*5.5 << 0.12*5.5 << 0.40*5.8 << 0.09*5.2 << 0.00*4.2 << 0.07*11.2;
124 | regenData << 0.06*10.5 << 0.05*5.5 << 0.04*5.5 << 0.06*5.8 << 0.02*5.2 << 0.07*4.2 << 0.25*11.2;
125 | fossil->setData(ticks, fossilData);
126 | nuclear->setData(ticks, nuclearData);
127 | regen->setData(ticks, regenData);
128 |
129 | if (mIsStackedBar) {
130 | regen->setStackingGap(1); // 设置堆积在其它柱状图上时的间距(像素)
131 | nuclear->setStackingGap(1);
132 |
133 | nuclear->moveAbove(fossil);
134 | regen->moveAbove(nuclear); // 将nuclear移到fossil之上
135 | } else if (mIsGroupBar) {
136 | QCPBarsGroup *group = new QCPBarsGroup(customPlot);
137 |
138 | QList bars;
139 | bars << fossil << nuclear << regen;
140 |
141 | foreach (QCPBars *bar, bars) {
142 | // 设置柱状图的宽度类型为以key坐标轴计算宽度的大小,其实默认就是这种方式
143 | bar->setWidthType(QCPBars::wtPlotCoords);
144 | bar->setWidth(bar->width() / bars.size()); // 设置柱状图的宽度大小
145 | group->append(bar); // 将柱状图加入柱状图分组中
146 | }
147 |
148 | group->setSpacingType(QCPBarsGroup::stAbsolute); // 设置组内柱状图的间距,按像素
149 | group->setSpacing(2); // 设置较小的间距值,这样看起来更紧凑
150 | } else {
151 | regen->setVisible(false);
152 | nuclear->setVisible(false);
153 | }
154 |
155 | customPlot->replot();
156 | }
157 |
158 |
159 |
--------------------------------------------------------------------------------
/src/examples/003_bar_chart_demo/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 |
6 | class QCustomPlot;
7 |
8 | class MainWindow : public QMainWindow
9 | {
10 | public:
11 | MainWindow(QWidget* parent = nullptr);
12 |
13 | void setupDemo(int index);
14 | void setupBarDemo(QCustomPlot* customPlot);
15 |
16 | protected:
17 | void reset();
18 |
19 | private:
20 | QCustomPlot* mCustomPlot;
21 | Qt::Orientation mOrientation;
22 |
23 | bool mIsStackedBar = false;
24 | bool mIsGroupBar = false;
25 | bool mTextVisible = false;
26 | };
27 |
28 | #endif // MAINWINDOW_H
29 |
--------------------------------------------------------------------------------
/src/examples/004_layout_demo/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/004_layout_demo/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/004_layout_demo/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 |
3 | #include
4 | #include
5 |
6 | #include "qcustomplot.h"
7 |
8 | MainWindow::MainWindow(QWidget *parent)
9 | : QMainWindow(parent)
10 | {
11 | mCustomPlot = new QCustomPlot;
12 |
13 | setWindowTitle("QCustomPlot: Layout Demo");
14 |
15 | QWidget* w = new QWidget;
16 | QVBoxLayout* layout = new QVBoxLayout;
17 | w->setLayout(layout);
18 | setCentralWidget(w);
19 |
20 | QStringList items;
21 | items << QString::fromLocal8Bit("对齐位置图例")
22 | << QString::fromLocal8Bit("自由位置图例")
23 | << QString::fromLocal8Bit("图例在QCustomPlot中");
24 | QComboBox* comboBox = new QComboBox;
25 | comboBox->addItems(items);
26 | connect(comboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::setupDemo);
27 |
28 | layout->addWidget(comboBox);
29 | layout->addWidget(mCustomPlot);
30 | setupDemo(0);
31 | }
32 |
33 | void MainWindow::reset()
34 | {
35 | delete mCustomPlot;
36 | mCustomPlot = new QCustomPlot;
37 | centralWidget()->layout()->addWidget(mCustomPlot);
38 |
39 | mOrientation = Qt::Vertical;
40 | mIsFreeLegend = false;
41 | mIsLegendInCustomPlot = false;
42 | }
43 |
44 | void MainWindow::setupDemo(int index)
45 | {
46 | reset();
47 |
48 | switch (index) {
49 | case 0: setupLayoutDemo(mCustomPlot); break;
50 | case 1: mIsFreeLegend = true; setupLayoutDemo(mCustomPlot); break;
51 | case 2: mIsLegendInCustomPlot = true; setupLayoutDemo(mCustomPlot); break;
52 | }
53 | }
54 |
55 | void MainWindow::setupQuadraticDemo(QCustomPlot *customPlot)
56 | {
57 | QVector x(101), y(101);
58 | for (int i = 0; i < 101; ++i) {
59 | x[i] = i / 50.0 - 1; // -1 到 1
60 | y[i] = x[i] * x[i];
61 | }
62 |
63 | auto keyAxis = customPlot->xAxis;
64 | auto valueAxis = customPlot->yAxis;
65 |
66 | if (mOrientation == Qt::Horizontal) {
67 | keyAxis = customPlot->yAxis;
68 | valueAxis = customPlot->xAxis;
69 | }
70 |
71 | customPlot->addGraph(keyAxis, valueAxis); // 添加一个曲线图QGraph
72 | customPlot->graph(0)->setName(QString::fromLocal8Bit("第一个示例")); // 设置曲线图的名字,用于QCPLegend显示
73 |
74 | customPlot->xAxis->setLabel("x"); // 设置x轴的标签
75 | customPlot->yAxis->setLabel("y");
76 | customPlot->graph(0)->setData(x, y);
77 | customPlot->rescaleAxes();
78 | }
79 |
80 | void MainWindow::setupLayoutDemo(QCustomPlot* customPlot)
81 | {
82 | setupQuadraticDemo(customPlot);
83 | customPlot->legend->setVisible(true); // 因为图例默认为隐藏的,所以让其显示
84 | // 设置图例标题
85 | QCPTextElement *title = new QCPTextElement(customPlot, QString::fromLocal8Bit("这是图例标题"), QFont("sans", 10, QFont::Bold));
86 | title->setMargins(QMargins(0, 6, 0, 10)); // 为了效果更好,添加一些边距
87 | title->setLayer("legend"); // 一定要把标题的层设置为legend层
88 | customPlot->legend->insertRow(0); // 插入一行
89 | customPlot->legend->addElement(0, 0, title); // 在第一行第一列添加标题
90 |
91 | if (mIsFreeLegend) {
92 | customPlot->axisRect()->insetLayout()->setInsetPlacement(0, QCPLayoutInset::ipFree);
93 | customPlot->axisRect()->insetLayout()->setInsetRect(0, QRectF(0.6, 0.0, 0.2, 0.2)); // 这里按比例给出图例的位置,在QCPAxisRect的(60%,40%)的位置,宽高分别为QCPAxisRect的(20%,20%)宽高的大小
94 | } else {
95 | customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignHCenter); // 对齐于QCPAxisRect中间的顶部
96 | }
97 |
98 | if (mIsLegendInCustomPlot) {
99 | QCPAxisRect* legendAxisRect = new QCPAxisRect(customPlot, false); // 不需要配置轴,因为我们只是把图例放在这里
100 | legendAxisRect->insetLayout()->addElement(customPlot->legend, QRectF(0, 0, 1, 1)); // 添加图例,充满整个legendAxisRect
101 |
102 | // 添加到QCustomPlot中
103 | customPlot->plotLayout()->insertRow(0);
104 | customPlot->plotLayout()->addElement(0, 0, legendAxisRect);
105 | customPlot->plotLayout()->setRowStretchFactor(0, 0.1);
106 |
107 | // 设置边距对齐
108 | QCPMarginGroup* marginGroup = new QCPMarginGroup(customPlot);
109 | customPlot->axisRect(0)->setMarginGroup(QCP::msLeft | QCP::msRight, marginGroup);
110 | customPlot->axisRect(1)->setMarginGroup(QCP::msLeft | QCP::msRight, marginGroup);
111 | }
112 |
113 | // 设置图表标题
114 | customPlot->plotLayout()->insertRow(0);
115 | customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, QString::fromLocal8Bit("这里是QCustomPlot的标题")));
116 | customPlot->plotLayout()->setMargins(QMargins(0, 10, 0, 10));
117 | }
118 |
119 |
--------------------------------------------------------------------------------
/src/examples/004_layout_demo/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 |
6 | class QCustomPlot;
7 | class QCPLayoutGrid;
8 |
9 | class MainWindow : public QMainWindow
10 | {
11 | public:
12 | MainWindow(QWidget* parent = nullptr);
13 |
14 | void setupDemo(int index);
15 | void setupQuadraticDemo(QCustomPlot *customPlot);
16 | void setupLayoutDemo(QCustomPlot* customPlot);
17 |
18 | protected:
19 | void reset();
20 |
21 | private:
22 | QCustomPlot* mCustomPlot;
23 | Qt::Orientation mOrientation;
24 |
25 | bool mIsFreeLegend = false;
26 | bool mIsLegendInCustomPlot = false;
27 | };
28 |
29 | #endif // MAINWINDOW_H
30 |
--------------------------------------------------------------------------------
/src/examples/005_axisrect_demo/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/005_axisrect_demo/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/005_axisrect_demo/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 | #include "qcustomplot.h"
3 |
4 | MainWindow::MainWindow(QWidget *parent)
5 | : QMainWindow(parent)
6 | {
7 | QCustomPlot* customPlot = new QCustomPlot;
8 | setCentralWidget(customPlot);
9 |
10 | setupAdvancedAxesDemo(customPlot);
11 | }
12 |
13 | void MainWindow::setupAdvancedAxesDemo(QCustomPlot *customPlot)
14 | {
15 | customPlot->plotLayout()->clear(); // 首先清空默认的轴矩形,让我们从头开始
16 | QCPAxisRect *wideAxisRect = new QCPAxisRect(customPlot, true); // 还记得setupDefaultAxes为true时的作用吗,忘了的话翻上去看吧
17 | wideAxisRect->setupFullAxesBox(true); // 让四个轴关联,并全部显示出来
18 | wideAxisRect->addAxis(QCPAxis::atLeft)->setTickLabelColor(QColor("#6050F8")); // 在左边多添加一个轴并且设置它的颜色
19 |
20 | QCPLayoutGrid *subLayout = new QCPLayoutGrid;
21 | customPlot->plotLayout()->addElement(0, 0, wideAxisRect); // 在第一行添加轴矩形
22 | customPlot->plotLayout()->addElement(1, 0, subLayout); // 在第二行添加一个子布局,后面会添加两个轴矩形在里面
23 |
24 | QCPAxisRect *subRectLeft = new QCPAxisRect(customPlot, false); // 不配置轴
25 | QCPAxisRect *subRectRight = new QCPAxisRect(customPlot, false);
26 |
27 | // 让右边的轴矩形固定大小
28 | subRectRight->setMaximumSize(100, 100);
29 | subRectRight->setMinimumSize(100, 100);
30 |
31 | subLayout->addElement(0, 0, subRectLeft); // 在第一列添加轴矩形
32 | subLayout->addElement(0, 1, subRectRight); // 在第二列添加轴矩形
33 |
34 | subRectLeft->addAxes(QCPAxis::atBottom | QCPAxis::atLeft); // 添加下轴和左轴
35 | subRectRight->addAxes(QCPAxis::atBottom | QCPAxis::atRight); // 添加下轴和右轴
36 | subRectLeft->axis(QCPAxis::atLeft)->ticker()->setTickCount(2); // 设置轴的刻度为一个固定的步进值
37 | subRectRight->axis(QCPAxis::atRight)->ticker()->setTickCount(2);
38 | subRectLeft->axis(QCPAxis::atBottom)->grid()->setVisible(true);
39 |
40 | // 保持一个好的习惯,将它们放置在相应的层
41 | foreach (auto *rect, customPlot->axisRects()) {
42 | foreach (auto *axis, rect->axes()) {
43 | axis->setLayer("axes");
44 | axis->grid()->setLayer("grid");
45 | }
46 | }
47 |
48 | // 准备数据
49 | QVector dataCos(21), dataGauss(50), dataRandom(100);
50 | QVector x3, y3;
51 | qsrand(3);
52 | for (int i=0; iaddGraph(wideAxisRect->axis(QCPAxis::atBottom), wideAxisRect->axis(QCPAxis::atLeft));
69 | mainGraphCos->data()->set(dataCos);
70 | mainGraphCos->valueAxis()->setRange(-1, 1);
71 | mainGraphCos->rescaleKeyAxis();
72 | mainGraphCos->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black), QBrush(Qt::white), 6));
73 | mainGraphCos->setPen(QPen(QColor(120, 120, 120), 2));
74 |
75 | QCPGraph *mainGraphGauss = customPlot->addGraph(wideAxisRect->axis(QCPAxis::atBottom), wideAxisRect->axis(QCPAxis::atLeft, 1));
76 | mainGraphGauss->data()->set(dataGauss);
77 | mainGraphGauss->setPen(QPen(QColor("#8070B8"), 2));
78 | mainGraphGauss->setBrush(QColor(110, 170, 110, 30));
79 | mainGraphCos->setChannelFillGraph(mainGraphGauss);
80 | mainGraphCos->setBrush(QColor(255, 161, 0, 50));
81 | mainGraphGauss->valueAxis()->setRange(0, 1000);
82 | mainGraphGauss->rescaleKeyAxis();
83 |
84 | QCPGraph *subGraphRandom = customPlot->addGraph(subRectLeft->axis(QCPAxis::atBottom), subRectLeft->axis(QCPAxis::atLeft));
85 | subGraphRandom->data()->set(dataRandom);
86 | subGraphRandom->setLineStyle(QCPGraph::lsImpulse);
87 | subGraphRandom->setPen(QPen(QColor("#FFA100"), 1.5));
88 | subGraphRandom->rescaleAxes();
89 |
90 | QCPBars *subBars = new QCPBars(subRectRight->axis(QCPAxis::atBottom), subRectRight->axis(QCPAxis::atRight));
91 | subBars->setWidth(3/(double)x3.size());
92 | subBars->setData(x3, y3);
93 | subBars->setPen(QPen(Qt::black));
94 | subBars->setAntialiased(false);
95 | subBars->setAntialiasedFill(false);
96 | subBars->setBrush(QColor("#705BE8"));
97 | subBars->keyAxis()->setSubTicks(false);
98 | subBars->rescaleAxes();
99 |
100 | // 给柱状图一个固定步进轴
101 | QSharedPointer intTicker(new QCPAxisTickerFixed);
102 | intTicker->setTickStep(1.0);
103 | intTicker->setScaleStrategy(QCPAxisTickerFixed::ssMultiples);
104 | subBars->keyAxis()->setTicker(intTicker);
105 | }
106 |
107 |
--------------------------------------------------------------------------------
/src/examples/005_axisrect_demo/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 |
6 | class QCustomPlot;
7 |
8 | class MainWindow : public QMainWindow
9 | {
10 | public:
11 | MainWindow(QWidget* parent = nullptr);
12 |
13 | void setupAdvancedAxesDemo(QCustomPlot *customPlot);
14 |
15 | private:
16 |
17 | };
18 |
19 | #endif // MAINWINDOW_H
20 |
--------------------------------------------------------------------------------
/src/examples/006_dynamic_data_demo/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/006_dynamic_data_demo/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/006_dynamic_data_demo/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 | #include "qcustomplot.h"
3 |
4 | MainWindow::MainWindow(QWidget *parent)
5 | : QMainWindow(parent)
6 | {
7 | mCustomPlot = new QCustomPlot;
8 | setCentralWidget(mCustomPlot);
9 |
10 | setupDynamicData(mCustomPlot);
11 | }
12 |
13 | void MainWindow::setupDynamicData(QCustomPlot *customPlot)
14 | {
15 | customPlot->plotLayout()->insertRow(0);
16 | customPlot->plotLayout()->insertColumn(0);
17 |
18 | QCPAxisRect *legendRect = new QCPAxisRect(customPlot, false); // 不需要配置轴,因为我们只是把图例放在这里
19 | legendRect->setAutoMargins(QCP::msNone); // 不计算边距
20 | legendRect->insetLayout()->addElement(customPlot->legend, Qt::AlignCenter); // 放置图例
21 | customPlot->legend->setVisible(true);
22 | customPlot->legend->setFillOrder(QCPLayoutGrid::foColumnsFirst); // 横向图例
23 |
24 | customPlot->axisRect()->setAutoMargins(QCP::msBottom | QCP::msRight); // 只计算下边距和右边距
25 | customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, QString::fromLocal8Bit("动态数据"), QFont("sans", 12, QFont::Bold)));
26 | customPlot->plotLayout()->addElement(0, 1, legendRect);
27 | customPlot->plotLayout()->setRowStretchFactor(0, 0.1); // 让其尽可能小一点
28 | customPlot->plotLayout()->setColumnStretchFactor(0, 0.1);
29 |
30 | // 设置柱状图
31 | QCPBars *bar = new QCPBars(customPlot->xAxis, customPlot->yAxis2);
32 | bar->setName(QString::fromLocal8Bit("预购队列"));
33 | bar->setPen(Qt::NoPen);
34 | bar->setBrush(QColor(194, 53, 49));
35 |
36 | // 设置折线图
37 | QCPGraph *graph = customPlot->addGraph(customPlot->xAxis, customPlot->yAxis);
38 | graph->setName(QString::fromLocal8Bit("最新成交价"));
39 | graph->setPen(QPen(QColor(47, 69, 84), 2));
40 | graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor(47, 69, 84), QColor(Qt::white), 4));
41 |
42 | customPlot->yAxis->setLabel(QString::fromLocal8Bit("价格"));
43 | customPlot->yAxis->setRange(0, 30);
44 | customPlot->yAxis->setSubTicks(false); // 设置子刻度线不显示
45 | customPlot->yAxis->setTickLength(0, 6); // 设置刻度线内外的长度
46 | customPlot->yAxis2->setLabel(QString::fromLocal8Bit("预购量"));
47 | customPlot->yAxis2->setVisible(true);
48 | customPlot->yAxis2->setRange(0, 1200);
49 | customPlot->yAxis2->setSubTicks(false);
50 | customPlot->yAxis2->setTickLength(0, 6);
51 |
52 | // 这里之所以用 QCPAxisTickerText,而不用 QCPAxisTickerTime / QCPAxisTickerDateTime 是因为它们会自动计算刻度线的位置,这是我们不想要的
53 | QSharedPointer timeTicker(new QCPAxisTickerText);
54 | QSharedPointer indexTicker(new QCPAxisTickerText);
55 | customPlot->xAxis->setTicker(timeTicker);
56 | customPlot->xAxis->setSubTicks(false);
57 | customPlot->xAxis2->setVisible(true);
58 | customPlot->xAxis2->setSubTicks(false);
59 | customPlot->xAxis2->setTicker(indexTicker);
60 | connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange))); // 重要:让xAxis2与xAxis保持联动
61 |
62 | // 添加数据
63 | QVector datax, datay1, datay2;
64 | QTime now = QTime::currentTime();
65 | for (int i = 0; i < 8; ++i) {
66 | mLabels.insert(0, now.toString("hh:mm:ss")); // mLabels == QVector
67 | datax.insert(0, now.msecsSinceStartOfDay() / 1000.0); // 时间
68 | now = now.addMSecs(-2000);
69 |
70 | mIndexLabels.insert(0, QString::number(8 - i));
71 | datay1.insert(0, QRandomGenerator::global()->bounded(20) + 5); // 产生随机数,Qt 5.10 以下用qrand() % 20
72 | datay2.insert(0, QRandomGenerator::global()->bounded(1000));
73 | }
74 |
75 | mIndex = 8;
76 | mPositions = datax; // mPositions == QVector
77 |
78 | graph->setData(datax, datay1);
79 | bar->setData(datax, datay2);
80 |
81 | timeTicker->setTicks(mPositions, mLabels); // 设置刻度线位置和刻度标签
82 | indexTicker->setTicks(mPositions, mIndexLabels);
83 |
84 | customPlot->xAxis->rescale();
85 | customPlot->xAxis->scaleRange(1.1); // 稍微缩放一下,以显示全部
86 |
87 | connect(&dataTimer, SIGNAL(timeout()), this, SLOT(dynamicDataSlot()));
88 | dataTimer.start(2000); // 2秒刷新一次
89 | }
90 |
91 | void MainWindow::dynamicDataSlot()
92 | {
93 | QCPBars *bar = static_cast(mCustomPlot->plottable(0));
94 |
95 | // 1. 去除之前的数据
96 | // 移除第一个数据
97 | bar->data()->remove(mPositions.first());
98 | mCustomPlot->graph(0)->data()->remove(mPositions.first());
99 |
100 | mPositions.removeFirst();
101 | mLabels.removeFirst();
102 | mIndexLabels.removeFirst();
103 |
104 | // 2. 添加新增数据
105 | // 计算当前时间
106 | double key = QTime::currentTime().msecsSinceStartOfDay() / 1000.0;
107 | QString label = QTime::currentTime().toString("hh:mm:ss");
108 |
109 | mCustomPlot->graph(0)->addData(key, QRandomGenerator::global()->bounded(20) + 5);
110 | bar->addData(key, QRandomGenerator::global()->bounded(1000));
111 |
112 | mPositions.push_back(key);
113 | mLabels.push_back(label);
114 | mIndexLabels.push_back(QString::number(++mIndex));
115 |
116 | // 3. 重新设置轴并刷新图表
117 | QCPAxisTickerText *timeTicker = static_cast(mCustomPlot->xAxis->ticker().data());
118 | timeTicker->setTicks(mPositions, mLabels); // 重新设置x轴
119 |
120 | QCPAxisTickerText *indexTicker = static_cast(mCustomPlot->xAxis2->ticker().data());
121 | indexTicker->setTicks(mPositions, mIndexLabels);
122 |
123 | mCustomPlot->xAxis->rescale();
124 | mCustomPlot->xAxis->scaleRange(1.1);
125 |
126 | mCustomPlot->replot();
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/src/examples/006_dynamic_data_demo/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 | #include
6 |
7 | class QCustomPlot;
8 |
9 | class MainWindow : public QMainWindow
10 | {
11 | Q_OBJECT
12 | public:
13 | MainWindow(QWidget* parent = nullptr);
14 |
15 | void setupDynamicData(QCustomPlot *customPlot);
16 |
17 | protected slots:
18 | void dynamicDataSlot();
19 |
20 | private:
21 |
22 | int mIndex;
23 | QVector mPositions;
24 | QVector mLabels;
25 | QVector mIndexLabels;
26 |
27 | QTimer dataTimer;
28 | QCustomPlot* mCustomPlot;
29 | };
30 |
31 | #endif // MAINWINDOW_H
32 |
--------------------------------------------------------------------------------
/src/examples/007_lemniscate_demo/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/007_lemniscate_demo/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/007_lemniscate_demo/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 | #include "qcustomplot.h"
3 |
4 | MainWindow::MainWindow(QWidget *parent)
5 | : QMainWindow(parent)
6 | {
7 | mCustomPlot = new QCustomPlot;
8 | setCentralWidget(mCustomPlot);
9 |
10 | setupLemniscateDemo(mCustomPlot);
11 | }
12 |
13 | void MainWindow::setupLemniscateDemo(QCustomPlot *customPlot)
14 | {
15 | QCPCurve *curve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);
16 | curve->setPen(QPen(Qt::red));
17 |
18 | // 由于我们是动态图,并且其范围不变化,所以预先设置好了范围
19 | customPlot->xAxis->setRange(-2.5, 12.5);
20 | customPlot->yAxis->setRange(-2.8, 2.8);
21 |
22 | connect(&dataTimer, SIGNAL(timeout()), this, SLOT(dynamicLemniscateSlot()));
23 | dataTimer.start(10); // 10ms刷新一次,实际上QTimer可能达不到这个精度
24 | }
25 |
26 | void MainWindow::dynamicLemniscateSlot()
27 | {
28 | static double t = -M_PI; // 定义起始t
29 | static bool reversed = false; // 为了重复绘制
30 |
31 | QCPCurve *curve = static_cast(mCustomPlot->plottable(0));
32 |
33 | // 伯努利双纽线(无穷大的符号)
34 | double x = -686*qCos(t) + 735*qCos(2*t) + 490*qSqrt(qPow(qSin(t), 4)) - 265;
35 | x /= (280*qCos(t) - 298);
36 | double y = 5*qSqrt(qPow(qSin(t), 4))*(10/qSin(t) - 7/qTan(t)) + 3*(35*qCos(t) - 33)*qSin(t);
37 | y = 7*y/(140*qCos(t) - 149);
38 |
39 | if (!reversed) { // 还未绘制完成
40 | t += 0.01;
41 | curve->data()->add(QCPCurveData(t, x, y));
42 | } else { // 绘制已经完成,倒退回去
43 | t -= 0.01;
44 | curve->data()->removeAfter(t); // 这里不能用remove,因为精度原因,remove并不能精确匹配,导致无法删除数据点
45 | }
46 |
47 | mCustomPlot->replot();
48 |
49 | // 重复绘制
50 | if (t >= M_PI) {
51 | t = M_PI;
52 | reversed = true;
53 | } else if (reversed && t <= -M_PI) {
54 | t = -M_PI;
55 | reversed = false;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/examples/007_lemniscate_demo/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 | #include
6 |
7 | class QCustomPlot;
8 |
9 | class MainWindow : public QMainWindow
10 | {
11 | Q_OBJECT
12 | public:
13 | MainWindow(QWidget* parent = nullptr);
14 |
15 | void setupLemniscateDemo(QCustomPlot *customPlot);
16 |
17 | protected slots:
18 | void dynamicLemniscateSlot();
19 |
20 | private:
21 | QTimer dataTimer;
22 | QCustomPlot* mCustomPlot;
23 | };
24 |
25 | #endif // MAINWINDOW_H
26 |
--------------------------------------------------------------------------------
/src/examples/008_smooth_graph_demo_01/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/008_smooth_graph_demo_01/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/008_smooth_graph_demo_01/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 | #include "qcpsmoothcurve.h"
3 |
4 | MainWindow::MainWindow(QWidget *parent)
5 | : QMainWindow(parent)
6 | {
7 | mCustomPlot = new QCustomPlot;
8 | mCustomPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
9 | setCentralWidget(mCustomPlot);
10 | setupSmoothCurveDemo(mCustomPlot);
11 | }
12 |
13 | void MainWindow::setupSmoothCurveDemo(QCustomPlot *customPlot)
14 | {
15 | QVector xdata = { 1, 2, 3, 4, 5, 6, 7 };
16 | QVector ydata = { 820, 932, 901, 934, 1290, 1330, 1320 };
17 |
18 | QCPSmoothCurve *graph = new QCPSmoothCurve(customPlot->xAxis, customPlot->yAxis);
19 | graph->setPen(QPen(Qt::red, 2));
20 | graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor(Qt::red), QColor(Qt::white), 6));
21 | graph->setData(xdata, ydata);
22 | graph->setSmooth(true);
23 |
24 | customPlot->xAxis->setRange(0, 8);
25 | customPlot->yAxis->setRange(0, 1500);
26 | }
27 |
28 |
--------------------------------------------------------------------------------
/src/examples/008_smooth_graph_demo_01/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 | #include
6 |
7 | class QCustomPlot;
8 |
9 | class MainWindow : public QMainWindow
10 | {
11 | Q_OBJECT
12 | public:
13 | MainWindow(QWidget* parent = nullptr);
14 |
15 | void setupSmoothCurveDemo(QCustomPlot *customPlot);
16 |
17 | private:
18 | QCustomPlot* mCustomPlot;
19 | };
20 |
21 | #endif // MAINWINDOW_H
22 |
--------------------------------------------------------------------------------
/src/examples/009_smooth_graph_demo_02/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/009_smooth_graph_demo_02/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/009_smooth_graph_demo_02/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 | #include "qcpsmoothcurve.h"
3 |
4 | MainWindow::MainWindow(QWidget *parent)
5 | : QMainWindow(parent)
6 | {
7 | mCustomPlot = new QCustomPlot;
8 | mCustomPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
9 | setCentralWidget(mCustomPlot);
10 | setupSmoothCurveDemo(mCustomPlot);
11 | }
12 |
13 | void MainWindow::setupSmoothCurveDemo(QCustomPlot *customPlot)
14 | {
15 | QVector xdata = { 1, 2, 3, 4, 5, 6, 7 };
16 | QVector ydata = { 820, 932, 901, 934, 1290, 1330, 1320 };
17 |
18 | QCPSmoothCurve *graph = new QCPSmoothCurve(customPlot->xAxis, customPlot->yAxis);
19 | graph->setPen(QPen(Qt::red, 2));
20 | graph->setBrush(QColor(208,110,107)); // 设置了填充色即可填充曲线与0点线之间的区域
21 | graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor(Qt::red), QColor(Qt::white), 6));
22 | graph->setData(xdata, ydata);
23 | graph->setSmooth(true);
24 |
25 | double offset = 500;
26 | QVector ydata1 = { 820 - offset, 880 - offset, 901 - offset, 934 - offset, 1290 - offset, 1330 - offset, 1320 - offset };
27 | QCPSmoothCurve *graph1 = new QCPSmoothCurve(customPlot->xAxis, customPlot->yAxis);
28 | graph1->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor(Qt::blue), QColor(Qt::white), 6));
29 | graph1->setData(xdata, ydata1);
30 | graph1->setSmooth(true);
31 |
32 | graph->setChannelFillGraph(graph1); // 设置与其它曲线填充
33 |
34 | customPlot->xAxis->setRange(0, 8);
35 | customPlot->yAxis->setRange(0, 1500);
36 | }
37 |
38 |
--------------------------------------------------------------------------------
/src/examples/009_smooth_graph_demo_02/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 | #include
6 |
7 | class QCustomPlot;
8 |
9 | class MainWindow : public QMainWindow
10 | {
11 | Q_OBJECT
12 | public:
13 | MainWindow(QWidget* parent = nullptr);
14 |
15 | void setupSmoothCurveDemo(QCustomPlot *customPlot);
16 |
17 | private:
18 | QCustomPlot* mCustomPlot;
19 | };
20 |
21 | #endif // MAINWINDOW_H
22 |
--------------------------------------------------------------------------------
/src/examples/012_stretch_item_demo/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | get_filename_component(CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} NAME)
2 | project(${CURRENT_SOURCE_DIR})
3 |
4 | find_package(Qt5Widgets)
5 |
6 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
7 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
8 |
9 | add_executable(${PROJECT_NAME} ${ALL_INCLUDES} ${ALL_SOURCES})
10 |
11 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets qcustomplot)
12 |
--------------------------------------------------------------------------------
/src/examples/012_stretch_item_demo/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "mainwindow.h"
3 |
4 | int main(int argc, char* argv[])
5 | {
6 | QApplication a(argc, argv);
7 |
8 | MainWindow w;
9 | w.resize(800, 600);
10 | w.show();
11 |
12 | return a.exec();
13 | }
14 |
--------------------------------------------------------------------------------
/src/examples/012_stretch_item_demo/mainwindow.cpp:
--------------------------------------------------------------------------------
1 | #include "mainwindow.h"
2 | #include "qcpplot.h"
3 |
4 | MainWindow::MainWindow(QWidget *parent)
5 | : QMainWindow(parent)
6 | {
7 | mCustomPlot = new QCPPlot;
8 | setCentralWidget(mCustomPlot);
9 | setupStretchItemDemo(mCustomPlot);
10 | }
11 |
12 | void MainWindow::setupStretchItemDemo(QCustomPlot *plot)
13 | {
14 | auto customPlot = qobject_cast(plot);
15 | customPlot->setInteractions(QCP::iSelectItems | QCP::iRangeZoom | QCP::iRangeDrag);
16 | QCPItemRect *rect = new QCPItemRect(customPlot);
17 | customPlot->sizeHandleManager()->addItem(rect);
18 | rect->setBrush(Qt::red);
19 | rect->setSelectedBrush(Qt::red);
20 |
21 | QCPItemLine *line = new QCPItemLine(customPlot);
22 | customPlot->sizeHandleManager()->addItem(line);
23 |
24 | QCPItemCurve *curve = new QCPItemCurve(customPlot);
25 | customPlot->sizeHandleManager()->addItem(curve);
26 | customPlot->sizeHandleManager()->setLineVisible(curve, true);
27 |
28 | QCPItemText *text = new QCPItemText(customPlot);
29 | text->setText(QString::fromLocal8Bit("试着拖动我!"));
30 | customPlot->sizeHandleManager()->addItem(text);
31 |
32 | QCPItemBracket *bracket = new QCPItemBracket(customPlot);
33 | customPlot->sizeHandleManager()->addItem(bracket);
34 |
35 | QCPItemEllipse *ellipse = new QCPItemEllipse(customPlot);
36 | customPlot->sizeHandleManager()->addItem(ellipse);
37 | customPlot->sizeHandleManager()->setLineVisible(ellipse, true);
38 |
39 | // QCPItemPixmap *pixmap = new QCPItemPixmap(customPlot);
40 | // pixmap->setPixmap(QPixmap(":/sun.png"));
41 | // customPlot->sizeHandleManager()->addItem(pixmap);
42 |
43 | QCPItemStraightLine *straightLine = new QCPItemStraightLine(customPlot);
44 | customPlot->sizeHandleManager()->addItem(straightLine);
45 |
46 | QCPItemTracer *tracer = new QCPItemTracer(customPlot);
47 | customPlot->sizeHandleManager()->addItem(tracer);
48 | }
49 |
--------------------------------------------------------------------------------
/src/examples/012_stretch_item_demo/mainwindow.h:
--------------------------------------------------------------------------------
1 | #ifndef MAINWINDOW_H
2 | #define MAINWINDOW_H
3 |
4 | #include
5 | #include
6 |
7 | class QCustomPlot;
8 |
9 | class MainWindow : public QMainWindow
10 | {
11 | Q_OBJECT
12 | public:
13 | MainWindow(QWidget* parent = nullptr);
14 |
15 | void setupStretchItemDemo(QCustomPlot *customPlot);
16 |
17 | private:
18 | QCustomPlot* mCustomPlot;
19 | };
20 |
21 | #endif // MAINWINDOW_H
22 |
--------------------------------------------------------------------------------
/src/examples/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | set(CMAKE_INCLUDE_CURRENT_DIR ON)
2 | set(CMAKE_AUTOMOC ON)
3 | set(CMAKE_CXX_STANDARD 11)
4 | set(CMAKE_CXX_STANDARD_REQUIRED ON)
5 | add_definitions(-DQCUSTOMPLOT_USE_LIBRARY)
6 |
7 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../qcustomplot)
8 | link_directories(${ROOT_PATH}/bin)
9 |
10 | add_subdirectory(001_start)
11 | add_subdirectory(003_bar_chart_demo)
12 | add_subdirectory(004_layout_demo)
13 | add_subdirectory(005_axisrect_demo)
14 | add_subdirectory(006_dynamic_data_demo)
15 | add_subdirectory(007_lemniscate_demo)
16 | add_subdirectory(008_smooth_graph_demo_01)
17 | add_subdirectory(009_smooth_graph_demo_02)
18 | add_subdirectory(012_stretch_item_demo)
19 |
20 |
--------------------------------------------------------------------------------
/src/qcustomplot/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | project(qcustomplot)
2 |
3 | set(CMAKE_INCLUDE_CURRENT_DIR ON)
4 | set(CMAKE_AUTOMOC ON)
5 | set(CMAKE_CXX_STANDARD 11)
6 | set(CMAKE_CXX_STANDARD_REQUIRED ON)
7 | add_definitions(-DQCUSTOMPLOT_COMPILE_LIBRARY)
8 |
9 | find_package(Qt5Widgets)
10 | find_package(Qt5PrintSupport)
11 |
12 | file(GLOB ALL_SOURCES "*.cpp" "*.c")
13 | file(GLOB ALL_INCLUDES "*.hpp" "*.h")
14 |
15 | add_library(${PROJECT_NAME} SHARED ${ALL_INCLUDES} ${ALL_SOURCES})
16 |
17 | target_link_libraries(${PROJECT_NAME} Qt5::Widgets Qt5::PrintSupport)
18 |
19 | install(TARGETS ${PROJECT_NAME}
20 | LIBRARY DESTINATION ${ROOT_PATH}/bin)
21 |
--------------------------------------------------------------------------------
/src/qcustomplot/GPL.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpplot.cpp:
--------------------------------------------------------------------------------
1 | #include "qcpplot.h"
2 |
3 | QCPPlot::QCPPlot(QWidget *parent)
4 | : QCustomPlot(parent)
5 | , mSizeHandleManager(new QCPSizeHandleManager(this))
6 | {
7 |
8 | }
9 |
10 | void QCPPlot::mousePressEvent(QMouseEvent *event)
11 | {
12 | mMousePressPos = event->pos();
13 | mMouseHasMoved = false;
14 | mLastMousePos = mMousePressPos;
15 |
16 | if (event->button() == Qt::LeftButton) {
17 | processPointSelection(event);
18 | if (selectedItems().count()) {
19 | emit mousePress(event);
20 | replot(rpQueuedReplot);
21 | return;
22 | }
23 | }
24 |
25 | QCustomPlot::mousePressEvent(event);
26 | }
27 |
28 | void QCPPlot::mouseMoveEvent(QMouseEvent *event)
29 | {
30 | QCustomPlot::mouseMoveEvent(event);
31 |
32 | if (mMouseHasMoved && (event->buttons() & Qt::LeftButton)) {
33 | auto items = selectedItems();
34 | for (auto item : items) {
35 | if (auto sizeHandle = qobject_cast(item))
36 | mSizeHandleManager->onItemResize(sizeHandle, event->pos() - mLastMousePos);
37 | else
38 | mSizeHandleManager->onItemMove(item, event->pos() - mLastMousePos);
39 | }
40 |
41 | mLastMousePos = event->pos();
42 | if (items.count())
43 | replot(rpQueuedReplot);
44 | }
45 | }
46 |
47 | void QCPPlot::mouseReleaseEvent(QMouseEvent *event)
48 | {
49 | QCustomPlot::mouseReleaseEvent(event);
50 | if (event->button() == Qt::LeftButton) {
51 | if (auto item = itemAt(event->pos(), true)) {
52 | item->setSelected(false);
53 | replot(rpQueuedReplot);
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpplot.h:
--------------------------------------------------------------------------------
1 | #ifndef QCPPLOT_H
2 | #define QCPPLOT_H
3 |
4 | #include "qcpsizehandlemanager.h"
5 |
6 | class QCP_LIB_DECL QCPPlot : public QCustomPlot
7 | {
8 | Q_OBJECT
9 | public:
10 | explicit QCPPlot(QWidget* parent = nullptr);
11 |
12 | QCPSizeHandleManager* sizeHandleManager() const { return mSizeHandleManager; }
13 |
14 | protected:
15 | void mousePressEvent(QMouseEvent *event) override;
16 | void mouseMoveEvent(QMouseEvent *event) override;
17 | void mouseReleaseEvent(QMouseEvent *event) override;
18 |
19 | protected:
20 | QCPSizeHandleManager* mSizeHandleManager;
21 | QPointF mLastMousePos;
22 | };
23 |
24 | #endif // QCPPLOT_H
25 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpsizehandle.cpp:
--------------------------------------------------------------------------------
1 | #include "qcpsizehandle.h"
2 |
3 | QCPSizeHandle::QCPSizeHandle(QCustomPlot *parentPlot, QCPAbstractItem *attachItem)
4 | : QCPAbstractItem(parentPlot)
5 | , position(createPosition(QLatin1String("position")))
6 | , mHovered(false)
7 | , mAttachItem(attachItem)
8 | {
9 | setBrush(QColor("#436EEE"));
10 | setHoveredBrush(QColor("#1C86EE"));
11 | setSelectedBrush(QColor("#3A5FCD"));
12 | setSize(8);
13 | setLayer(QLatin1String("overlay"));
14 | }
15 |
16 | QCPSizeHandle::~QCPSizeHandle()
17 | {
18 | }
19 |
20 | void QCPSizeHandle::setBrush(const QBrush &brush)
21 | {
22 | mBrush = brush;
23 | }
24 |
25 | void QCPSizeHandle::setSelectedBrush(const QBrush &brush)
26 | {
27 | mSelectedBrush = brush;
28 | }
29 |
30 | void QCPSizeHandle::setHoveredBrush(const QBrush &brush)
31 | {
32 | mHoveredBrush = brush;
33 | }
34 |
35 | void QCPSizeHandle::setSize(double size)
36 | {
37 | mSize = size;
38 | }
39 |
40 | double QCPSizeHandle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
41 | {
42 | Q_UNUSED(details)
43 | if (onlySelectable && !mSelectable)
44 | return -1;
45 |
46 | QPointF itemPos = position->pixelPosition();
47 | QRectF rect = QRectF(itemPos.x() - mSize * 0.5, itemPos.y() - mSize * 0.5, mSize, mSize);
48 | bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
49 | return rectDistance(rect, pos, filledRect);
50 | }
51 |
52 | void QCPSizeHandle::draw(QCPPainter *painter)
53 | {
54 | QRectF rect(0, 0, mSize, mSize);
55 |
56 | rect.moveTopLeft(position->pixelPosition() - QPointF(mSize * 0.5, mSize * 0.5));
57 |
58 | if (rect.intersects(clipRect())) {
59 | painter->setPen(Qt::NoPen);
60 | painter->setBrush(mainBrush());
61 | painter->drawRect(rect);
62 | }
63 | }
64 |
65 | //void QCPSizeHandle::hoverEnterEvent(QHoverEvent *event)
66 | //{
67 | // Q_UNUSED(event)
68 | // mHovered = true;
69 | // layer()->replot();
70 | //}
71 |
72 | //void QCPSizeHandle::hoverLeaveEvent(QHoverEvent *event)
73 | //{
74 | // Q_UNUSED(event)
75 | // mHovered = true;
76 | // layer()->replot();
77 | //}
78 |
79 | QBrush QCPSizeHandle::mainBrush() const
80 | {
81 | return selected() ? mSelectedBrush : (mHovered ? mHoveredBrush : mBrush);
82 | }
83 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpsizehandle.h:
--------------------------------------------------------------------------------
1 | #ifndef QCPSIZEHANDLE_H
2 | #define QCPSIZEHANDLE_H
3 |
4 | #include "qcustomplot.h"
5 |
6 | class QCP_LIB_DECL QCPSizeHandle : public QCPAbstractItem
7 | {
8 | Q_OBJECT
9 | public:
10 | explicit QCPSizeHandle(QCustomPlot *parentPlot, QCPAbstractItem* attachItem);
11 | ~QCPSizeHandle();
12 |
13 | void setBrush(const QBrush &brush);
14 | void setSelectedBrush(const QBrush &brush);
15 | void setHoveredBrush(const QBrush &brush);
16 | void setSize(double size);
17 |
18 | QCPAbstractItem* attachItem() const { return mAttachItem; }
19 |
20 | QCPItemPosition * const position;
21 |
22 | public:
23 | virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE;
24 |
25 | protected:
26 | bool mHovered;
27 | double mSize;
28 | QBrush mBrush;
29 | QBrush mSelectedBrush;
30 | QBrush mHoveredBrush;
31 | QCPAbstractItem* mAttachItem;
32 |
33 | virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
34 | // virtual void hoverEnterEvent(QHoverEvent *event) Q_DECL_OVERRIDE;
35 | // virtual void hoverLeaveEvent(QHoverEvent *event) Q_DECL_OVERRIDE;
36 |
37 | QBrush mainBrush() const;
38 | };
39 |
40 | #endif // QCPSIZEHANDLE_H
41 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpsizehandlemanager.cpp:
--------------------------------------------------------------------------------
1 | #include "qcpsizehandlemanager.h"
2 |
3 | QCPSizeHandleManager::QCPSizeHandleManager(QCustomPlot *parent)
4 | : QCPAbstractItem(parent)
5 | {
6 | setLayer("overlay");
7 | }
8 |
9 | bool QCPSizeHandleManager::addItem(QCPAbstractItem *item)
10 | {
11 | if (!item || item->positions().isEmpty() || qobject_cast(item))
12 | return false;
13 |
14 | if (mItems.contains(item))
15 | return true;
16 |
17 | QList handles;
18 | for (auto position : item->positions()) {
19 | auto *handle = new QCPSizeHandle(mParentPlot, item);
20 | handle->position->setParentAnchor(position);
21 | handles.append(handle);
22 | }
23 |
24 | if (handles.count() == 1)
25 | handles.at(0)->setVisible(false);
26 |
27 | auto itemData = QSharedPointer::create();
28 | itemData->resizable = handles.count() > 1;
29 | itemData->handles = handles;
30 | mItems.insert(item, itemData);
31 | return true;
32 | }
33 |
34 | void QCPSizeHandleManager::removeItem(QCPAbstractItem *item)
35 | {
36 | mItems.remove(item);
37 | }
38 |
39 | void QCPSizeHandleManager::setLineVisible(QCPAbstractItem *item, bool visible)
40 | {
41 | if (auto itemData = mItems.value(item))
42 | itemData->lineVisible = visible;
43 | }
44 |
45 | void QCPSizeHandleManager::setLinePen(QCPAbstractItem *item, const QPen &pen)
46 | {
47 | if (auto itemData = mItems.value(item))
48 | itemData->linePen = pen;
49 | }
50 |
51 | void QCPSizeHandleManager::setItemMovable(QCPAbstractItem *item, bool movable)
52 | {
53 | if (auto itemData = mItems.value(item))
54 | itemData->movable = movable;
55 | }
56 |
57 | void QCPSizeHandleManager::setItemResizable(QCPAbstractItem *item, bool resizable)
58 | {
59 | if (auto itemData = mItems.value(item))
60 | itemData->resizable = resizable && itemData->handles.count() > 1;
61 | }
62 |
63 | double QCPSizeHandleManager::selectTest(const QPointF &, bool , QVariant *) const
64 | {
65 | return -1;
66 | }
67 |
68 | void QCPSizeHandleManager::onItemMove(QCPAbstractItem *item, const QPointF &delta)
69 | {
70 | if (!item || !mItems.contains(item))
71 | return;
72 |
73 | auto itemData = mItems.value(item);
74 | if (!itemData->movable)
75 | return;
76 |
77 | for (auto position : item->positions())
78 | position->setPixelPosition(position->pixelPosition() + delta);
79 | }
80 |
81 | void QCPSizeHandleManager::onItemResize(QCPSizeHandle *sizeHandle, const QPointF &delta)
82 | {
83 | if (!sizeHandle)
84 | return;
85 |
86 | auto itemData = mItems.value(sizeHandle->attachItem());
87 | if (!itemData || !itemData->resizable)
88 | return;
89 |
90 | if (auto parentPosition = static_cast(sizeHandle->position->parentAnchor()))
91 | {
92 | parentPosition->setPixelPosition(parentPosition->pixelPosition() + delta);
93 | }
94 | }
95 |
96 | void QCPSizeHandleManager::draw(QCPPainter *painter)
97 | {
98 | QMapIterator, QSharedPointer> i(mItems);
99 | QList destoryedItems;
100 |
101 | while (i.hasNext()) {
102 | i.next();
103 |
104 | if (!i.key()) {
105 | destoryedItems.append(i.key());
106 | continue;
107 | }
108 |
109 | auto itemData = i.value();
110 | if (!itemData->lineVisible || itemData->handles.count() < 2)
111 | continue;
112 |
113 | painter->setPen(itemData->linePen);
114 |
115 | QVector lines;
116 |
117 | QCPItemAnchor *topLeft = nullptr;
118 | QCPItemAnchor *bottomRight = nullptr;
119 |
120 | for (auto handle : itemData->handles) {
121 | if (handle->position->parentAnchor()->name() == QLatin1String("topLeft"))
122 | topLeft = handle->position->parentAnchor();
123 | if (handle->position->parentAnchor()->name() == QLatin1String("bottomRight"))
124 | bottomRight = handle->position->parentAnchor();
125 | lines.push_back(handle->position->pixelPosition());
126 | }
127 |
128 | if (topLeft && bottomRight) {
129 | lines.clear();
130 |
131 | lines.push_back(topLeft->pixelPosition());
132 | lines.push_back(QPointF(bottomRight->pixelPosition().x(), topLeft->pixelPosition().y()));
133 | lines.push_back(bottomRight->pixelPosition());
134 | lines.push_back(QPointF(topLeft->pixelPosition().x(), bottomRight->pixelPosition().y()));
135 | lines.push_back(topLeft->pixelPosition());
136 | painter->drawPolyline(lines);
137 | } else
138 | painter->drawLines(lines);
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpsizehandlemanager.h:
--------------------------------------------------------------------------------
1 | #ifndef QCPSIZEHANDLEMANAGER_H
2 | #define QCPSIZEHANDLEMANAGER_H
3 |
4 | #include "qcpsizehandle.h"
5 |
6 | class QCPSizeHandle;
7 | class QCP_LIB_DECL QCPSizeHandleManager : public QCPAbstractItem
8 | {
9 | Q_OBJECT
10 | public:
11 | explicit QCPSizeHandleManager(QCustomPlot *parent);
12 |
13 | bool addItem(QCPAbstractItem* item);
14 | void removeItem(QCPAbstractItem* item);
15 |
16 | void setLineVisible(QCPAbstractItem* item, bool visible);
17 | void setLinePen(QCPAbstractItem* item, const QPen& pen);
18 | void setItemMovable(QCPAbstractItem* item, bool movable);
19 | void setItemResizable(QCPAbstractItem* item, bool resizable);
20 |
21 | double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const override;
22 |
23 | public slots:
24 | void onItemMove(QCPAbstractItem* item, const QPointF &delta);
25 | void onItemResize(QCPSizeHandle* sizeHandle, const QPointF &delta);
26 |
27 | protected:
28 | void draw(QCPPainter *painter) override;
29 |
30 | protected:
31 | struct ItemData {
32 | bool lineVisible = false;
33 | bool movable = true;
34 | bool resizable = true;
35 | QPen linePen = QPen(Qt::blue, 1, Qt::DashLine);
36 | QList handles;
37 | };
38 |
39 | QMap, QSharedPointer> mItems;
40 | };
41 |
42 | #endif // QCPSIZEHANDLEMANAGER_H
43 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpsmoothcurve.cpp:
--------------------------------------------------------------------------------
1 | #include "qcpsmoothcurve.h"
2 |
3 | class SmoothCurveGenerator
4 | {
5 | protected:
6 | static QPainterPath generateSmoothCurveImp(const QVector &points) {
7 | QPainterPath path;
8 | int len = points.size();
9 |
10 | if (len < 2) {
11 | return path;
12 | }
13 |
14 | QVector firstControlPoints;
15 | QVector secondControlPoints;
16 | calculateControlPoints(points, &firstControlPoints, &secondControlPoints);
17 |
18 | path.moveTo(points[0].x(), points[0].y());
19 |
20 | // Using bezier curve to generate a smooth curve.
21 | for (int i = 0; i < len - 1; ++i) {
22 | path.cubicTo(firstControlPoints[i], secondControlPoints[i], points[i+1]);
23 | }
24 |
25 | return path;
26 | }
27 | public:
28 | static QPainterPath generateSmoothCurve(const QVector &points) {
29 | QPainterPath result;
30 | QVector lineData(QVector(points.constBegin(), points.constEnd()));
31 | result.addPath(generateSmoothCurveImp(lineData));
32 | return result;
33 | }
34 |
35 | static QPainterPath generateSmoothCurve(const QPainterPath &basePath, const QVector &points) {
36 | if (points.isEmpty()) return basePath;
37 |
38 | QPainterPath path = basePath;
39 | int len = points.size();
40 | if (len == 1) {
41 | path.lineTo(points.at(0));
42 | return path;
43 | }
44 |
45 | QVector firstControlPoints;
46 | QVector secondControlPoints;
47 | calculateControlPoints(points, &firstControlPoints, &secondControlPoints);
48 |
49 | path.lineTo(points.at(0));
50 | for (int i = 0; i < len - 1; ++i)
51 | path.cubicTo(firstControlPoints[i], secondControlPoints[i], points[i+1]);
52 |
53 | return path;
54 | }
55 |
56 | static void calculateFirstControlPoints(double *&result, const double *rhs, int n) {
57 | result = new double[n];
58 | double *tmp = new double[n];
59 | double b = 2.0;
60 | result[0] = rhs[0] / b;
61 |
62 | // Decomposition and forward substitution.
63 | for (int i = 1; i < n; i++) {
64 | tmp[i] = 1 / b;
65 | b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
66 | result[i] = (rhs[i] - result[i - 1]) / b;
67 | }
68 |
69 | for (int i = 1; i < n; i++) {
70 | result[n - i - 1] -= tmp[n - i] * result[n - i]; // Backsubstitution.
71 | }
72 |
73 | delete[] tmp;
74 | }
75 |
76 | static void calculateControlPoints(const QVector &knots,
77 | QVector *firstControlPoints,
78 | QVector *secondControlPoints) {
79 | int n = knots.size() - 1;
80 |
81 | firstControlPoints->reserve(n);
82 | secondControlPoints->reserve(n);
83 |
84 | for (int i = 0; i < n; ++i) {
85 | firstControlPoints->append(QPointF());
86 | secondControlPoints->append(QPointF());
87 | }
88 |
89 | if (n == 1) {
90 | // Special case: Bezier curve should be a straight line.
91 | // P1 = (2P0 + P3) / 3
92 | (*firstControlPoints)[0].rx() = (2 * knots[0].x() + knots[1].x()) / 3;
93 | (*firstControlPoints)[0].ry() = (2 * knots[0].y() + knots[1].y()) / 3;
94 |
95 | // P2 = 2P1 – P0
96 | (*secondControlPoints)[0].rx() = 2 * (*firstControlPoints)[0].x() - knots[0].x();
97 | (*secondControlPoints)[0].ry() = 2 * (*firstControlPoints)[0].y() - knots[0].y();
98 |
99 | return;
100 | }
101 |
102 | // Calculate first Bezier control points
103 | double *xs = nullptr;
104 | double *ys = nullptr;
105 | double *rhsx = new double[n]; // Right hand side vector
106 | double *rhsy = new double[n]; // Right hand side vector
107 |
108 | // Set right hand side values
109 | for (int i = 1; i < n - 1; ++i) {
110 | rhsx[i] = 4 * knots[i].x() + 2 * knots[i + 1].x();
111 | rhsy[i] = 4 * knots[i].y() + 2 * knots[i + 1].y();
112 | }
113 | rhsx[0] = knots[0].x() + 2 * knots[1].x();
114 | rhsx[n - 1] = (8 * knots[n - 1].x() + knots[n].x()) / 2.0;
115 | rhsy[0] = knots[0].y() + 2 * knots[1].y();
116 | rhsy[n - 1] = (8 * knots[n - 1].y() + knots[n].y()) / 2.0;
117 |
118 | // Calculate first control points coordinates
119 | calculateFirstControlPoints(xs, rhsx, n);
120 | calculateFirstControlPoints(ys, rhsy, n);
121 |
122 | // Fill output control points.
123 | for (int i = 0; i < n; ++i) {
124 | (*firstControlPoints)[i].rx() = xs[i];
125 | (*firstControlPoints)[i].ry() = ys[i];
126 |
127 | if (i < n - 1) {
128 | (*secondControlPoints)[i].rx() = 2 * knots[i + 1].x() - xs[i + 1];
129 | (*secondControlPoints)[i].ry() = 2 * knots[i + 1].y() - ys[i + 1];
130 | } else {
131 | (*secondControlPoints)[i].rx() = (knots[n].x() + xs[n - 1]) / 2;
132 | (*secondControlPoints)[i].ry() = (knots[n].y() + ys[n - 1]) / 2;
133 | }
134 | }
135 |
136 | delete xs;
137 | delete ys;
138 | delete[] rhsx;
139 | delete[] rhsy;
140 | }
141 | };
142 |
143 |
144 | QCPSmoothCurve::QCPSmoothCurve(QCPAxis *keyAxis, QCPAxis *valueAxis)
145 | : QCPGraph(keyAxis, valueAxis)
146 | , mSmooth(true)
147 | {
148 |
149 | }
150 |
151 | void QCPSmoothCurve::draw(QCPPainter *painter)
152 | {
153 | if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
154 | if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
155 | if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
156 |
157 | if (mSmooth && mLineStyle == lsLine) {
158 | QVector data(mDataContainer->begin(), mDataContainer->end());
159 | mLines = dataToLines(data);
160 | mSegments = getNonNanSegments(&mLines, mKeyAxis->orientation());
161 | mSmoothPaths = QVector();
162 | mSmoothPaths.reserve(mSegments.count());
163 | for (int i = 0; i < mSegments.count(); ++i) {
164 | const auto& segment = mSegments.at(i);
165 | QVector points(mLines.constBegin() + segment.begin(), mLines.constBegin() + segment.end());
166 | mSmoothPaths.append(SmoothCurveGenerator::generateSmoothCurve(points));
167 | }
168 | qDebug() << mSegments.count() << mSmoothPaths.count() << mLines.count();
169 | }
170 |
171 | QCPGraph::draw(painter);
172 |
173 | mSegments = QVector();
174 | mSmoothPaths = QVector();
175 | mLines = QVector();
176 | }
177 |
178 | void QCPSmoothCurve::drawLinePlot(QCPPainter *painter, const QVector &lines) const
179 | {
180 | if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) {
181 | applyDefaultAntialiasingHint(painter);
182 | if (mSmooth && mLineStyle == lsLine) {
183 | QPainterPath clipPath = painter->clipPath();
184 | QPainterPath clipRect = getLinesClipPath(lines);
185 |
186 | painter->setClipPath(clipPath.intersected(clipRect));
187 | for (int i = 0; i < mSmoothPaths.count(); ++i) {
188 | if (mSmoothPaths.at(i).intersects(clipRect))
189 | painter->drawPath(mSmoothPaths.at(i));
190 | }
191 |
192 | painter->setClipPath(clipPath);
193 | }
194 | else
195 | drawPolyline(painter, lines);
196 | }
197 | }
198 |
199 | void QCPSmoothCurve::drawFill(QCPPainter *painter, QVector *lines) const
200 | {
201 | if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
202 | if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
203 |
204 | applyFillAntialiasingHint(painter);
205 | QVector segments = getNonNanSegments(lines, keyAxis()->orientation());
206 | if (!mChannelFillGraph) // 与0点线围成的区域
207 | {
208 | // draw base fill under graph, fill goes all the way to the zero-value-line:
209 | for (int i=0; iclipPath();
212 | QPainterPath clipRect;
213 | auto path = getSmoothFillPath(lines, segments.at(i), &clipRect);
214 | painter->setClipPath(clipPath.intersected(clipRect));
215 | painter->drawPath(path); // 平滑曲线
216 | painter->setClipPath(clipPath);
217 | }
218 | else
219 | painter->drawPolygon(getFillPolygon(lines, segments.at(i))); // 折线
220 | } else // 与其它QCPGraph围成的区域
221 | {
222 | // draw fill between this graph and mChannelFillGraph:
223 | auto channelFillGraph = qobject_cast(mChannelFillGraph.data());
224 | if (!channelFillGraph) {
225 | qDebug() << "ChannelFillGraph must be QCPSmoothCurve";
226 | return;
227 | }
228 | QVector otherLines;
229 | channelFillGraph->getLines(&otherLines, QCPDataRange(0, channelFillGraph->dataCount()));
230 | if (!otherLines.isEmpty())
231 | {
232 | QVector otherSegments = getNonNanSegments(&otherLines, channelFillGraph->keyAxis()->orientation());
233 | QVector > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
234 | for (int i=0; imLineStyle == lsLine) && (mSmooth || channelFillGraph->mSmooth))
236 | painter->drawPath(getSmoothChannelFillPath(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); // 平滑曲线
237 | else
238 | painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); // 折线
239 | }
240 | }
241 | }
242 | }
243 |
244 | QPainterPath QCPSmoothCurve::getSmoothFillPath(const QVector *lineData, QCPDataRange segment, QPainterPath *clipPath) const
245 | {
246 | // 只有一个点构不成填充区域
247 | if (segment.size() < 2)
248 | return QPainterPath();
249 |
250 | *clipPath = getLinesClipPath(getFillPolygon(lineData, segment));
251 |
252 | QPainterPath result;
253 | for (int i = 0; i < mSmoothPaths.count(); ++i) {
254 | QCPDataRange subSegment = mSegments.at(i);
255 | if (subSegment.size() < 2)
256 | continue;
257 |
258 | QPointF start = getFillBasePoint(mLines.at(subSegment.begin()));
259 | QPointF end = getFillBasePoint(mLines.at(subSegment.end() - 1));
260 | QPainterPath path = mSmoothPaths.at(i);
261 | path.lineTo(end);
262 | path.lineTo(start);
263 | path.lineTo(mLines.at(subSegment.begin()));
264 | result.addPath(path);
265 |
266 | }
267 | return result;
268 | }
269 |
270 | QPainterPath QCPSmoothCurve::getSmoothChannelFillPath(const QVector *thisData, QCPDataRange thisSegment,
271 | const QVector *otherData, QCPDataRange otherSegment) const
272 | {
273 | QPainterPath result;
274 | auto channelFillGraph = qobject_cast(mChannelFillGraph.data());
275 | if (!channelFillGraph) {
276 | qDebug() << "ChannelFillGraph must be QCPSmoothCurve";
277 | return result;
278 | }
279 |
280 | QCPAxis *keyAxis = mKeyAxis.data();
281 | QCPAxis *valueAxis = mValueAxis.data();
282 | if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
283 | if (!channelFillGraph->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return result; }
284 |
285 | if (channelFillGraph->mKeyAxis.data()->orientation() != keyAxis->orientation())
286 | return result; // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
287 |
288 | if (thisData->isEmpty()) return result;
289 | QVector thisSegmentData(thisSegment.size());
290 | QVector otherSegmentData(otherSegment.size());
291 | std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
292 | std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
293 | // pointers to be able to swap them, depending which data range needs cropping:
294 | QVector *staticData = &thisSegmentData;
295 | QVector *croppedData = &otherSegmentData;
296 |
297 | //! [1] 以下为添加的内容
298 | if (mSmooth)
299 | result = SmoothCurveGenerator::generateSmoothCurve(thisSegmentData);
300 | else
301 | result.addPolygon(thisSegmentData);
302 | if (channelFillGraph->mSmooth && channelFillGraph->mLineStyle == lsLine) { // mChannelFillGraph也是平滑曲线
303 | QVector otherSegmentDataReverse(otherSegmentData.size());
304 | for (int i = otherSegmentData.size() - 1; i >= 0; --i)
305 | otherSegmentDataReverse[otherSegmentData.size() - i - 1] = otherSegmentData.at(i);
306 | result = SmoothCurveGenerator::generateSmoothCurve(result, otherSegmentDataReverse);
307 | } else { // mChannelFillGraph 是折线
308 | // mLineStyle != lsLine 会导致闪烁,目前还不知道什么原因造成
309 | for (int i = otherSegmentData.size() - 1; i >= 0; --i)
310 | result.lineTo(otherSegmentData.at(i));
311 | }
312 | //! [1]
313 |
314 | // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
315 | if (keyAxis->orientation() == Qt::Horizontal)
316 | {
317 | // x is key
318 | // crop lower bound:
319 | if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
320 | qSwap(staticData, croppedData);
321 | const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
322 | if (lowBound == -1) return result; // key ranges have no overlap
323 | //! [2] 以下为添加的内容
324 | QPointF firstPoint = QPointF(croppedData->at(0).x(), valueAxis->coordToPixel(valueAxis->range().upper)); // 注意这里只裁剪到了轴矩形的可见区域
325 | //! [2]
326 | croppedData->remove(0, lowBound);
327 | // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
328 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
329 | double slope;
330 | if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
331 | slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
332 | else
333 | slope = 0;
334 | (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
335 | (*croppedData)[0].setX(staticData->first().x());
336 |
337 | //! [3] 以下为添加的内容
338 | QPointF lastPoint = QPointF(staticData->first().x(), valueAxis->coordToPixel(valueAxis->range().lower)); // 注意这里只裁剪到了轴矩形的可见区域
339 | QPainterPath droppedPath;
340 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
341 | result -= droppedPath; // 裁掉多余区域
342 | //! [3]
343 |
344 | // crop upper bound:
345 | if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
346 | qSwap(staticData, croppedData);
347 | int highBound = findIndexAboveX(croppedData, staticData->last().x());
348 | if (highBound == -1) return result; // key ranges have no overlap
349 | //! [4] 以下为添加的内容
350 | firstPoint = QPointF(croppedData->last().x(), valueAxis->coordToPixel(valueAxis->range().lower)); // 注意这里只裁剪到了轴矩形的可见区域
351 | //! [4]
352 | croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
353 | // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
354 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
355 | const int li = croppedData->size()-1; // last index
356 | if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
357 | slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
358 | else
359 | slope = 0;
360 | (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
361 | (*croppedData)[li].setX(staticData->last().x());
362 |
363 | //! [5] 以下为添加的内容
364 | lastPoint = QPointF(staticData->last().x(), valueAxis->coordToPixel(valueAxis->range().upper));
365 | droppedPath = QPainterPath();
366 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
367 | result -= droppedPath; // 裁掉多余区域
368 | //! [5]
369 | } else // mKeyAxis->orientation() == Qt::Vertical
370 | {
371 | // y is key
372 | // crop lower bound:
373 | if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
374 | qSwap(staticData, croppedData);
375 | int lowBound = findIndexBelowY(croppedData, staticData->first().y());
376 | if (lowBound == -1) return result; // key ranges have no overlap
377 | //! [6] 以下为添加的内容
378 | QPointF firstPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().upper), croppedData->first().y());
379 | //! [6]
380 | croppedData->remove(0, lowBound);
381 | // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
382 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
383 | double slope;
384 | if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
385 | slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
386 | else
387 | slope = 0;
388 | (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
389 | (*croppedData)[0].setY(staticData->first().y());
390 |
391 | //! [7] 以下为添加的内容
392 | QPointF lastPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().lower), staticData->first().y());
393 | QPainterPath droppedPath;
394 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
395 | result -= droppedPath;
396 | //! [7]
397 |
398 | // crop upper bound:
399 | if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
400 | qSwap(staticData, croppedData);
401 | int highBound = findIndexAboveY(croppedData, staticData->last().y());
402 | if (highBound == -1) return result; // key ranges have no overlap
403 | //! [8] 以下为添加的内容
404 | firstPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().lower), croppedData->last().y());
405 | //! [8]
406 | croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
407 | // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
408 | if (croppedData->size() < 2) return result; // need at least two points for interpolation
409 | int li = croppedData->size()-1; // last index
410 | if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
411 | slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
412 | else
413 | slope = 0;
414 | (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
415 | (*croppedData)[li].setY(staticData->last().y());
416 |
417 | //! [9] 以下为添加的内容
418 | lastPoint = QPointF(valueAxis->coordToPixel(valueAxis->range().upper), staticData->last().y());
419 | droppedPath = QPainterPath();
420 | droppedPath.addRect(QRectF(firstPoint, lastPoint).normalized());
421 | result -= droppedPath;
422 | //! [9]
423 | }
424 | return result;
425 | }
426 |
427 | QPainterPath QCPSmoothCurve::getLinesClipPath(const QPolygonF &polygon) const
428 | {
429 | QPainterPath result;
430 | QRectF br = polygon.boundingRect();
431 | if (br.isNull()) return result;
432 |
433 | if (mKeyAxis->orientation() == Qt::Horizontal) {
434 | QPointF firstPoint = QPointF(br.x(), mValueAxis->coordToPixel(mValueAxis->range().upper));
435 | QPointF lastPoint = QPointF(br.x() + br.width(), mValueAxis->coordToPixel(mValueAxis->range().lower));
436 | result.addRect(QRectF(firstPoint, lastPoint).normalized());
437 | } else {
438 | QPointF firstPoint = QPointF(mValueAxis->coordToPixel(mValueAxis->range().lower), br.y());
439 | QPointF lastPoint = QPointF(mValueAxis->coordToPixel(mValueAxis->range().upper), br.y() + br.height());
440 | result.addRect(QRectF(firstPoint, lastPoint).normalized());
441 | }
442 | return result;
443 | }
444 |
445 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcpsmoothcurve.h:
--------------------------------------------------------------------------------
1 | #ifndef QCPSMOOTHCURVE_H
2 | #define QCPSMOOTHCURVE_H
3 |
4 | #include "qcustomplot.h"
5 |
6 | class QCP_LIB_DECL QCPSmoothCurve : public QCPGraph
7 | {
8 | Q_OBJECT
9 | public:
10 | explicit QCPSmoothCurve(QCPAxis *keyAxis, QCPAxis *valueAxis);
11 |
12 | void setSmooth(bool smooth) { mSmooth = smooth; }
13 |
14 | protected:
15 | void draw(QCPPainter *painter) override;
16 | void drawLinePlot(QCPPainter *painter, const QVector &lines) const override;
17 | void drawFill(QCPPainter *painter, QVector *lines) const override;
18 |
19 | protected:
20 | QPainterPath getSmoothFillPath(const QVector *lineData, QCPDataRange segment, QPainterPath *clipPath) const;
21 | QPainterPath getSmoothChannelFillPath(const QVector *thisData, QCPDataRange thisSegment,
22 | const QVector *otherData, QCPDataRange otherSegment) const;
23 | QRectF getLinesRect(const QVector& lineData);
24 | QPainterPath getLinesClipPath(const QPolygonF& polygon) const;
25 |
26 | protected:
27 | bool mSmooth;
28 | QVector mSmoothPaths;
29 | QVector mSegments;
30 | QVector mLines;
31 | };
32 |
33 | #endif // QCPSMOOTHCURVE_H
34 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcptextbars.cpp:
--------------------------------------------------------------------------------
1 | #include "qcptextbars.h"
2 |
3 | QCPTextBars::QCPTextBars(QCPAxis *keyAxis, QCPAxis *valueAxis)
4 | : QCPBars(keyAxis, valueAxis)
5 | , mTextAlignment(Qt::AlignCenter)
6 | , mTextVisible(false)
7 | , mSpacing(5)
8 | , mFont(QFont(QLatin1String("sans serif"), 12))
9 | {
10 |
11 | }
12 |
13 | void QCPTextBars::setTextAlignment(Qt::Alignment alignment)
14 | {
15 | mTextAlignment = alignment;
16 | }
17 |
18 | void QCPTextBars::setTextVisible(bool visible)
19 | {
20 | mTextVisible = visible;
21 | }
22 |
23 | void QCPTextBars::setSpacing(double spacing)
24 | {
25 | mSpacing = spacing;
26 | }
27 |
28 | void QCPTextBars::setFont(const QFont &font)
29 | {
30 | mFont = font;
31 | }
32 |
33 | void QCPTextBars::draw(QCPPainter *painter)
34 | {
35 | if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
36 | if (mDataContainer->isEmpty()) return;
37 |
38 | QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
39 | getVisibleDataBounds(visibleBegin, visibleEnd);
40 |
41 | // loop over and draw segments of unselected/selected data:
42 | QList selectedSegments, unselectedSegments, allSegments;
43 | getDataSegments(selectedSegments, unselectedSegments);
44 | allSegments << unselectedSegments << selectedSegments;
45 | for (int i=0; i= unselectedSegments.size();
48 | QCPBarsDataContainer::const_iterator begin = visibleBegin;
49 | QCPBarsDataContainer::const_iterator end = visibleEnd;
50 | mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
51 | if (begin == end)
52 | continue;
53 |
54 | for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
55 | {
56 | // check data validity if flag set:
57 | #ifdef QCUSTOMPLOT_CHECK_DATA
58 | if (QCP::isInvalidData(it->key, it->value))
59 | qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
60 | #endif
61 | // draw bar:
62 | if (isSelectedSegment && mSelectionDecorator)
63 | {
64 | mSelectionDecorator->applyBrush(painter);
65 | mSelectionDecorator->applyPen(painter);
66 | } else
67 | {
68 | painter->setBrush(mBrush);
69 | painter->setPen(mPen);
70 | }
71 | applyDefaultAntialiasingHint(painter);
72 |
73 | QRectF barRect = getBarRect(it->key, it->value);
74 | painter->drawPolygon(barRect);
75 |
76 | if (mTextVisible)
77 | drawText(painter, it->key, it->value, barRect);
78 | }
79 | }
80 |
81 | // draw other selection decoration that isn't just line/scatter pens and brushes:
82 | if (mSelectionDecorator)
83 | mSelectionDecorator->drawDecoration(painter, selection());
84 | }
85 |
86 | void QCPTextBars::drawText(QCPPainter *painter, double key, double value, const QRectF &barRect)
87 | {
88 | Q_UNUSED(key)
89 |
90 | painter->setFont(mFont);
91 | QString text = QString::number(value, 'g', 2); // 取得当前value轴的值,保留两位精度
92 |
93 | QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, text); // 计算文字所占用的大小
94 |
95 | if (mKeyAxis.data()->orientation() == Qt::Horizontal) { // 当key轴为水平轴的时候
96 | if (mKeyAxis.data()->axisType() == QCPAxis::atTop) // 上轴,移动文字到柱状图下面
97 | textRect.moveTopLeft(barRect.bottomLeft() + QPointF(0, mSpacing));
98 | else // 下轴,移动文字到柱状图上面
99 | textRect.moveBottomLeft(barRect.topLeft() - QPointF(0, mSpacing));
100 | textRect.setWidth(barRect.width());
101 | painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);
102 | } else { // 当key轴为竖直轴的时候
103 | if (mKeyAxis.data()->axisType() == QCPAxis::atLeft) // 左轴,移动文字到柱状图右边
104 | textRect.moveTopLeft(barRect.topRight() + QPointF(mSpacing, 0));
105 | else // 右轴,移动文字到柱状图左边
106 | textRect.moveTopRight(barRect.topLeft() - QPointF(mSpacing, 0));
107 | textRect.setHeight(barRect.height());
108 | painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/qcustomplot/qcptextbars.h:
--------------------------------------------------------------------------------
1 | #ifndef QCPTEXTBARS_H
2 | #define QCPTEXTBARS_H
3 |
4 | #include "qcustomplot.h"
5 |
6 | class QCP_LIB_DECL QCPTextBars : public QCPBars
7 | {
8 | Q_OBJECT
9 | public:
10 | explicit QCPTextBars(QCPAxis *keyAxis, QCPAxis *valueAxis);
11 |
12 | Qt::Alignment textAligment() const { return mTextAlignment; }
13 | bool textVisible() const { return mTextVisible; }
14 | double spacing() const { return mSpacing; }
15 | QFont font() const { return mFont; }
16 |
17 | void setTextAlignment(Qt::Alignment alignment);
18 | void setTextVisible(bool visible);
19 | void setSpacing(double spacing);
20 | void setFont(const QFont &font);
21 |
22 | protected:
23 | void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
24 |
25 | virtual void drawText(QCPPainter* painter, double key, double value, const QRectF& barRect);
26 |
27 | protected:
28 | Qt::Alignment mTextAlignment; // 文字对齐方式
29 | bool mTextVisible; // 文字是否可见
30 | double mSpacing; // 文字与柱状图的间距,这里按像素大小
31 | QFont mFont; // 文字使用的字体
32 | };
33 |
34 | #endif // QCPTEXTBARS_H
35 |
--------------------------------------------------------------------------------