說明
使用 QCustomPlot 繪圖庫輔助開發(fā)時整理的學習筆記。同系列文章目錄可見 《繪圖庫 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
兩個文件。官網(wǎng) - QCustomPlot - SettingUp 有對 QCustomPlot 的使用方法做介紹。
2. 使用方法
2.1 將源文件添加進項目
把 qcustomplot.h
與 qcustomplot.cpp
兩個文件放在項目路徑下,然后右鍵 項目名 -> 添加現(xiàn)有文件...,選擇 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 繪制圖像
完成以上幾步后,點擊左下方的綠色三角,運行項目,會得到一個空的坐標軸,如下所示:
在這個區(qū)域內(nèi),可以使用 QCustomPlot
提供的方法繪制函數(shù)曲線圖、參數(shù)曲線圖、柱狀圖、箱線圖、熱力圖等,詳見幫助文檔,或本人同系列博客。這里提供一個示例,在合適的地方添加如下代碼:
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();
再次點擊左下方的綠色三角,運行項目,會得到以下曲線圖:
文章來源:http://www.zghlxwxcb.cn/news/detail-488828.html
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
即是下載所得的兩個文件。文章來源地址http://www.zghlxwxcb.cn/news/detail-488828.html
到了這里,關(guān)于【QCustomPlot】使用方法(源碼方式)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!