Qt 生態中主流的圖表庫有 Qwt 和 KdChart,Qwt 以輕量、專業著稱,適合科學計算與工控界面。本文記錄一個最小化 Demo:在 Qt 4.8.5 環境下,利用 Qwt 繪製正弦波,並啟用縮放與平移交互。
DEFINES += QWT_DLL CONFIG += qwt LIBS += -L"D:/Qt/4.8.5/lib" -lqwtd INCLUDEPATH += D:/Qt/4.8.5/include/QtQwt # 請根據實際安裝路徑修改上述路徑
#include#include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { QApplication a(argc, argv); // 1. 創建繪圖畫布 QwtPlot plot(QwtText("CppQwtExample1")); plot.resize(640, 400); // 2. 設置坐標軸標題與範圍 plot.setAxisTitle(QwtPlot::xBottom, "x→"); plot.setAxisTitle(QwtPlot::yLeft, "y→"); plot.setAxisScale(QwtPlot::xBottom, 0.0, 2.0 * M_PI); plot.setAxisScale(QwtPlot::yLeft, -1.0, 1.0); // 3. 顯示圖例(右側) plot.insertLegend(new QwtLegend(), QwtPlot::RightLegend); // 4. 啟用交互:滾輪縮放、左鍵平移 (void) new QwtPlotMagnifier(plot.canvas()); (void) new QwtPlotPanner(plot.canvas()); // 5. 準備數據:正弦波采樣點 QVector xs, ys; for (double x = 0; x < 2.0 * M_PI; x += (M_PI / 10.0)) { xs.append(x); ys.append(qSin(x)); } // 6. 構建曲線數據對象 QwtPointArrayData *data = new QwtPointArrayData(xs, ys); // 7. 配置曲線屬性 QwtPlotCurve curve("Sine"); curve.setData(data); curve.setStyle(QwtPlotCurve::Lines); // 折線風格 curve.setCurveAttribute(QwtPlotCurve::Fitted, true); // 平滑曲線 curve.setPen(QPen(Qt::blue)); // 藍色畫筆 curve.attach(&plot); // 掛載到 plot plot.show(); return a.exec(); }
QwtPlot:繪圖主窗口,管理坐標系、圖例、畫布。QwtPlotCurve:曲線項,持有數據、畫筆、風格。QwtPointArrayData:基於 QVector 的數據適配器。QwtPlotMagnifier/QwtPlotPanner:事件過濾器,分別實現縮放與平移。程序啟動後顯示一個帶網格、圖例、可縮放平移的正弦波曲線圖,適合作為儀表監控、波形分析模塊的起點。
提示:Qt5 版本需調整模組引用(
QT += widgets printsupport)並適配 Qwt 6.1+ 的命名空間變更。