說明
使用 QCustomPlot 繪圖庫輔助開發時整理的學習筆記,同系列文章目錄可見 《繪圖庫 QCustomPlot 學習筆記》目錄,本篇介紹 QCustomPlot 的一種使用方法,通過包含原始碼的方式進行使用,這也是最常用的方法,示例中使用的 QCustomPlot 版本為 Version 2.1.1,
- 說明
- 1. 下載原始碼
- 2. 使用方法
- 2.1 將源檔案添加進專案
- 2.2 修改 .pro 工程檔案
- 2.3 將 QWidget 提升為 QCustomPlot
- 2.4 繪制影像
- 3. 示例工程原始碼
- 3.1 檔案 demoQCP.pro
- 3.2 檔案 main.cpp
- 3.3 檔案 mainwindow.h
- 3.4 檔案 mainwindow.cpp
- 3.5 其他檔案
1. 下載原始碼
詳見本人另一篇博客 【QCustomPlot】下載,使用時,只需要 qcustomplot.h 與 qcustomplot.cpp 兩個檔案,官網 - QCustomPlot - SettingUp 有對 QCustomPlot 的使用方法做介紹,
2. 使用方法
2.1 將源檔案添加進專案
把 qcustomplot.h 與 qcustomplot.cpp 兩個檔案放在專案路徑下,然后右鍵 專案名 -> 添加現有檔案...,選擇 qcustomplot.h 與 qcustomplot.cpp,

2.2 修改 .pro 工程檔案
由于 QCustomPlot 具有匯出 PDF 的功能,使用到了 printsupport 模塊,因此需要在 .pro 工程檔案中添加這一模塊,如下所示,注意前面的版本條件,
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport

2.3 將 QWidget 提升為 QCustomPlot
在設計界面中,右鍵某個 QWidget 控制元件,點擊 提升為...,

在彈出的對話框中,先在 ”提升的類名稱“ 一欄寫上 QCustomPlot,注意大小寫要完全一致,然后點擊 添加 按鈕,最后點擊 提升 按鈕,

至此,這個 QWidget 控制元件就被提升為了 QCustomPlot 控制元件,可以進行繪圖了,

2.4 繪制影像
完成以上幾步后,點擊左下方的綠色三角,運行專案,會得到一個空的坐標軸,如下所示:

在這個區域內,可以使用 QCustomPlot 提供的方法繪制函式曲線圖、引數曲線圖、柱狀圖、箱線圖、熱力圖等,詳見幫助檔案,或本人同系列博客,這里提供一個示例,在合適的地方添加如下代碼:
QVector<double> x = {0,1,2,3,4,5,6,7,8,9};
QVector<double> y = {0,2,4,9,16,25,36,49,64,81};
ui->widget->addGraph();
ui->widget->graph(0)->setData(x, y);
ui->widget->graph(0)->rescaleAxes();
ui->widget->replot();
再次點擊左下方的綠色三角,運行專案,會得到以下曲線圖:

3. 示例工程原始碼
3.1 檔案 demoQCP.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport
TARGET = demoQCP
TEMPLATE = app
SOURCES += \
main.cpp \
mainwindow.cpp \
qcustomplot.cpp
HEADERS += \
mainwindow.h \
qcustomplot.h
FORMS += \
mainwindow.ui
3.2 檔案 main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
3.3 檔案 mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
3.4 檔案 mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 繪圖代碼
QVector<double> x = {0,1,2,3,4,5,6,7,8,9};
QVector<double> y = {0,2,4,9,16,25,36,49,64,81};
ui->widget->addGraph();
ui->widget->graph(0)->setData(x, y);
ui->widget->graph(0)->rescaleAxes();
ui->widget->replot();
}
MainWindow::~MainWindow()
{
delete ui;
}
3.5 其他檔案
除以上四個檔案外,還剩三個檔案:mainwindow.ui、qcustomplot.h、qcustomplot.cpp,其中 mainwindow.ui 是 Qt Creator 生成的默認 UI 檔案,界面中只多了一個提升后的 QCustomPlot 控制元件,可使用同樣步驟再次生成,qcustomplot.h 與 qcustomplot.cpp 即是下載所得的兩個檔案,
本文作者:木三百川
本文鏈接:https://www.cnblogs.com/young520/p/17489580.html
著作權宣告:本文系博主原創文章,著作權歸作者所有,商業轉載請聯系作者獲得授權,非商業轉載請附上出處鏈接,遵循 署名-非商業性使用-相同方式共享 4.0 國際版 (CC BY-NC-SA 4.0) 著作權協議,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/555498.html
標籤:其他
上一篇:Java 變數與基本資料型別
下一篇:返回列表
