首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

Qt QCustomPlot 繪圖入門:從安裝到第一條曲線

     編輯:C++ 入門

專案背景與工具選型

Qt 專案需繪製即時座標曲線,經比較 QChart、Qwt、QCustomPlot 等方案,最終選擇 QCustomPlot:API 直觀、文檔完善、支援多軸/多圖層/拖曳縮放,且單檔案頭文件+實現檔整合極簡單。

安裝與專案整合

  1. 官網下載:qcustomplot.com,建議下載完整包(含範例)
  2. 解壓至無中文路徑目錄
  3. Qt Creator 中右鍵專案 →「Add Existing Files」→ 選取 qcustomplot.h、qcustomplot.cpp
  4. .pro 檔確認包含:SOURCES += qcustomplot.cpp
    HEADERS += qcustomplot.h
  5. UI 設計器中拖入 QWidget,右鍵「Promote to...」提升為 QCustomPlot,提升類別名填 QCustomPlot,頭文件填 qcustomplot.h

核心概念速覽

  • QCustomPlot:繪圖區容器,繼承 QWidget
  • QCPGraph:單條曲線(資料序列),addGraph() 建立,graph(index) 存取
  • 四座標軸:xAxis/yAxis(預設顯示),xAxis2/yAxis2(頂部/右側,預設隱藏)
  • 資料容器:QVector<double> 或 QCPDataMap,配合 setData() 批量更新

第一個範例:繪製 y = x³ 曲線

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)
  • 高頻更新(>30 FPS)建議啟用 OpenGL 加速:graph->setAdaptiveSampling(true) 或使用 QCustomPlot::setOpenGl(true)(需 Qt 5.4+)

常見問題排查

現象原因解決
曲線不顯示座標軸範圍未設定呼叫 setRange() 或 rescaleAxes()
中文標籤亂碼字型不支援setLabelFont(QFont("Microsoft YaHei"))
記憶體持續增長未清理舊資料定期 data()->removeBefore(key)
編譯錯誤 undefined reference未將 cpp 加入專案檢查 .pro 檔 SOURCES

QCustomPlot 官方文檔極詳細,文檔頁 涵蓋所有類別與範例。本文僅為入門引導,進階功能(統計圖、色階圖、極座標等)請參考官方範例專案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved