Qt 專案需繪製即時座標曲線,經比較 QChart、Qwt、QCustomPlot 等方案,最終選擇 QCustomPlot:API 直觀、文檔完善、支援多軸/多圖層/拖曳縮放,且單檔案頭文件+實現檔整合極簡單。
qcustomplot.h、qcustomplot.cppSOURCES += qcustomplot.cppHEADERS += qcustomplot.hQWidget,右鍵「Promote to...」提升為 QCustomPlot,提升類別名填 QCustomPlot,頭文件填 qcustomplot.hQWidgetaddGraph() 建立,graph(index) 存取xAxis/yAxis(預設顯示),xAxis2/yAxis2(頂部/右側,預設隱藏)QVector<double> 或 QCPDataMap,配合 setData() 批量更新Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
ui->setupUi(this);
// 1. 準備資料
QVector<double> x(101), y(101);
for (int i = 0; i < 101; ++i) {
x[i] = i / 5.0 - 10; // -10 ~ +10
y[i] = x[i] * x[i] * x[i]; // y = x³
}
// 2. 新增曲線並設定資料
ui->qCustomPlot->addGraph(); // 索引 0
ui->qCustomPlot->graph(0)->setData(x, y);
// 3. 座標軸標籤與範圍
ui->qCustomPlot->xAxis->setLabel("x");
ui->qCustomPlot->yAxis->setLabel("y");
ui->qCustomPlot->xAxis->setRange(-11, 11);
ui->qCustomPlot->yAxis->setRange(-1100, 1100);
// 4. 觸發重繪(setData 內部已呼叫 replot,動態更新時需手動呼叫)
// ui->qCustomPlot->replot();
}
// 新增第二條曲線
ui->qCustomPlot->addGraph();
ui->qCustomPlot->graph(1)->setData(x, y2); // y2 為另一組資料
ui->qCustomPlot->graph(1)->setPen(QPen(Qt::red)); // 紅色曲線
ui->qCustomPlot->graph(1)->setName("y = sin(x)");
// 顯示圖例
ui->qCustomPlot->legend->setVisible(true);
ui->qCustomPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop|Qt::AlignRight);
// 啟用滑鼠互動:範圍拖曳、滾輪縮放、選取曲線
ui->qCustomPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
QCPGraph::data()->clear() + addData(key, value) 增量更新,避免重複分配xAxis->setRange(key - 30, key, Qt::AlignRight)graph->setAdaptiveSampling(true) 或使用 QCustomPlot::setOpenGl(true)(需 Qt 5.4+)| 現象 | 原因 | 解決 |
|---|---|---|
| 曲線不顯示 | 座標軸範圍未設定 | 呼叫 setRange() 或 rescaleAxes() |
| 中文標籤亂碼 | 字型不支援 | setLabelFont(QFont("Microsoft YaHei")) |
| 記憶體持續增長 | 未清理舊資料 | 定期 data()->removeBefore(key) |
編譯錯誤 undefined reference | 未將 cpp 加入專案 | 檢查 .pro 檔 SOURCES |
QCustomPlot 官方文檔極詳細,文檔頁 涵蓋所有類別與範例。本文僅為入門引導,進階功能(統計圖、色階圖、極座標等)請參考官方範例專案。