QCustomPlot?是一個基于 Qt 框架的輕量級 C++ 繪圖庫,專為高效繪制二維圖表(如曲線圖、柱狀圖、金融圖表等)而設計。相比 Qt Charts 模塊,它以?高性能?和?高度可定制性?著稱,尤其適合需要實時數據可視化的科學計算、工業監控和金融分析場景。
核心特性概覽
特性 | 說明 |
---|---|
輕量高效 | 僅需 2 個頭文件 + 1 個源碼文件,零外部依賴 |
實時性能 | 優化處理百萬級數據點,支持 OpenGL 加速 |
多圖層系統 | 支持無限圖層疊加,獨立坐標系 |
交互功能 | 內置縮放/平移/選擇/圖例拖拽等操作 |
豐富圖元 | 提供 20+ 可交互繪圖元素(箭頭、文本、追蹤線等) |
導出格式 | 支持 PNG/JPEG/PDF/SVG 矢量導出 |
跨平臺 | 兼容 Windows/macOS/Linux/嵌入式系統 |
核心組件解析
1.?繪圖核心 (QCustomPlot
?類)
QCustomPlot *plot = new QCustomPlot(parent);
坐標系系統:支持多軸(X/Y/頂部/右側軸)
圖層管理:通過?
QCPLayer
?實現元素分層渲染事件處理:鼠標/鍵盤交互事件接口
2.?數據容器 (QCPDataContainer
)
QVector<double> x(100), y(100);
// 填充數據...
QCPGraph *graph = plot->addGraph();
graph->setData(x, y);
內存優化:使用?
QSharedPointer
?管理大數據數據操作:支持數據排序、范圍篩選、NaN 處理
3.?核心圖元類型
圖元類型 | 說明 | 創建方法 |
---|---|---|
QCPGraph | 曲線圖 | addGraph() |
QCPBars | 柱狀圖 | new QCPBars(xAxis, yAxis) |
QCPColorMap | 熱力圖 | addColorMap() |
QCPFinancial | K線圖 | new QCPFinancial(xAxis, yAxis) |
QCPItem* | 交互元素 | new QCPItemLine(plot) |
?4.?交互元素示例
// 創建數據追蹤器
QCPItemTracer *tracer = new QCPItemTracer(plot);
tracer->setGraph(graph);
tracer->setGraphKey(5.0); // 定位到X=5.0的點// 添加十字坐標線
QCPItemStraightLine *vLine = new QCPItemStraightLine(plot);
vLine->point1->setCoords(5, 0); // (x,y)
vLine->point2->setCoords(5, 10);
基礎使用示例
1. 創建簡單曲線圖
// 創建繪圖區域
QCustomPlot *plot = new QCustomPlot(this);// 生成數據
QVector<double> x(101), y(101);
for (int i=0; i<101; ++i) {x[i] = i/50.0 - 1; // -1 到 1y[i] = x[i]*x[i]; // y = x2
}// 添加曲線
plot->addGraph();
plot->graph(0)->setData(x, y);// 設置坐標軸
plot->xAxis->setLabel("X Axis");
plot->yAxis->setLabel("Y Axis");
plot->rescaleAxes();// 重繪
plot->replot();
2. 實時數據更新
// 定時更新數據
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, [&]() {static double t = 0;plot->graph(0)->addData(t, qSin(t)); // 追加新數據點plot->xAxis->setRange(t-10, t); // 滾動X軸plot->replot();t += 0.1;
});
timer->start(50); // 20 FPS刷新
高級功能演示
1. 多圖層混合
// 主圖層:曲線圖
plot->addGraph();// 創建新圖層(在頂部顯示標注)
QCPLayer *annoLayer = new QCPLayer(plot, "annotations");
plot->addLayer("annotations", 0, QCustomPlot::limAbove); // 置于頂層// 在標注層添加文本
QCPItemText *textLabel = new QCPItemText(plot);
textLabel->setLayer(annoLayer);
textLabel->position->setCoords(5, 8);
textLabel->setText("峰值區域");
2. 自定義繪圖元素
// 創建自定義彩色柱狀圖
QCPBars *bars = new QCPBars(plot->xAxis, plot->yAxis);// 漸變著色
QVector<QColor> colors = {Qt::blue, Qt::green, Qt::red};
QSharedPointer<QCPColorGradient> gradient(new QCPColorGradient);
gradient->setColorStops({ {0, Qt::blue}, {0.5, Qt::green}, {1, Qt::red} });// 應用著色
bars->setBrush(QBrush(*gradient));
性能優化技巧
數據分塊加載
graph->setLineStyle(QCPGraph::lsNone); // 禁用連線
graph->setScatterStyle(QCPScatterStyle::ssDot); // 僅繪制點
OpenGL 加速
plot->setOpenGl(true); // 啟用GPU渲染
增量數據更新
// 僅追加新數據(避免全量重設)
graph->addData(newX, newY);
graph->data()->removeBefore(newX-visibleRange);
異步重繪
plot->setReplotTime(20); // 限制重繪頻率(ms)