之前介紹過基于QT的繪圖控件QCustomPlot的強大功能,詳見我之前的文章Qt中關于繪圖表QCustomPlot的使用。
今天突然翻出來,熟悉了一下,順便寫了個Demo做為記錄。
- QCustomPlot采用圖層的方式繪制圖像,通過addGraph()添加圖層資訊,然年後通過graph(int)擷取添加的圖層,然後在這個圖層上進行繪制。可以添加多個圖層;
- legend作為圖例,會自動的把各個圖層繪制資訊添加出來,使用者隻需要通過graph(0)->setName設定各個繪制示例的名稱;
- xAxis,yAxis作為坐标軸繪制顯示。
1.建立一個類,繼承自QCustomPlot:
#pragma once
#include "QCustomPlot.h"
class User2QCustomPlot : public QCustomPlot {
Q_OBJECT
public:
User2QCustomPlot(QWidget *parent);
~User2QCustomPlot();
void init();
};
#include "User2QCustomPlot.h"
User2QCustomPlot::User2QCustomPlot(QWidget *parent)
: QCustomPlot(parent) {
init();
}
User2QCustomPlot::~User2QCustomPlot() {
}
void User2QCustomPlot::init() {
//設定可以通過滑鼠拖動和滾軸縮放
setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
//設定X坐标軸
xAxis->setVisible(true);
xAxis->setLabel(QStringLiteral("X軸"));
xAxis->setRange(0, 100);
//設定Y坐标軸
yAxis->setVisible(true);
yAxis->setLabel(QStringLiteral("Y軸"));
yAxis->setRange(0, 100);
//添加圖層
addGraph();
graph()->setPen(QPen(QColor(255, 0, 255)));
graph()->setLineStyle(QCPGraph::LineStyle::lsLine);
QVector<double> xValue, yValue;
for (int i = 50; i < 200; i++) {
xValue.push_back(i*0.1);
yValue.push_back(i*0.5);
}
graph()->setData(xValue, yValue);
graph()->setBrush(QBrush(QColor(0, 255, 0)));
//添加圖層2
addGraph();
graph(1)->setPen(QPen(QColor(0, 0, 255)));
graph(1)->setLineStyle(QCPGraph::LineStyle::lsLine);
QVector<double> xValue2, yValue2;
for (int i = 0; i < 100; i++) {
xValue2.push_back(100 - i);
yValue2.push_back(i);
}
graph(1)->setData(xValue2, yValue2);
//顯示圖例
legend->setVisible(true);
graph(0)->setName(QStringLiteral("測試一"));
graph(1)->setName(QStringLiteral("測試二"));
}
2.布局UI
在界面上添加一個QWidget,然後[提升為…]
User2QCustomPlot
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2csQTQq1UMjRVTpR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLxQTN5EzMyIjMzITMwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
3.運作結果:
aaa