第一步、QcustomPlot是QT提供的一個第三方庫,在使用前需要在QcustomPlot官網上進行下載。
第二步、把解壓完的QcustomPlot壓縮包中的qcustomplot.h和qcustomplot.cpp文件添加到工程文件中來。使用時應先在源文件處點擊添加現有文件,把這兩個文件添加進來。
第三步、打開UI界面,把weiget控件添加到界面里,然后右鍵點擊控件,選擇提升
在提升的類名上寫QcustomPlot,最后點擊提升即可。
這樣QcustomPlot這個第三方庫就可以使用了。
以下是一簡單的曲線代碼。
.cpp文件
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QTime> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //設置鼠標點擊精度 ui->customPlot->setSelectionTolerance(1); for(int i=0;i<20;i++) { num[i]=0; } n=0; QTimer *t = new QTimer(this); t->start(500); connect(t,SIGNAL(timeout()),this,SLOT(graph_show())); connect(ui->customPlot,SIGNAL(mouseRelease(QMouseEvent*)),this,SLOT(mouseReleaseEvent(QMouseEvent*))); //connect(tracer,SIGNAL(mouseMove(QMouseEvent*)),this,SLOT(mouseMoveEvent(QMouseEvent*))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::graph_show() { n += PI/8; graph_show(ui->customPlot); } void MainWindow::graph_show(QCustomPlot *customPlot) { QVector<double> x(20),y(20); for(int i=0;i<19;i++) { num[i]=num[i+1]; } num[19]=n; for(int i=0;i<20;i++) { x[i] = i; y[i] = sin(num[i]); } //添加一條曲線 customPlot->addGraph(); //設置曲線的顏色 customPlot->graph(0)->setPen(QPen(Qt::red)); //給曲線傳遞兩個參數 customPlot->graph(0)->setData(x,y); //給曲線的橫縱坐標命名 customPlot->xAxis->setLabel("x"); customPlot->yAxis->setLabel("y"); //設置橫縱坐標的范圍 customPlot->xAxis->setRange(0,20); customPlot->yAxis->setRange(-3,3); //進行曲線重畫 customPlot->replot(); /* customPlot->setInteraction(QCP::iRangeZoom,true); customPlot->axisRect()->setRangeDrag(Qt::Vertical); customPlot->setInteraction(QCP::iRangeDrag,true); */ } void MainWindow::mouseReleaseEvent(QMouseEvent *e) { //排除非左鼠標鍵 if (e->button() != Qt::LeftButton) { return; } //獲取點擊的點坐標 QPointF ChickedPoint = e->pos(); //排除區間外鼠標點 if(!ui->customPlot->viewport().contains(e->pos())) { return; } //將像素坐標轉換為軸值 double currentx = ui->customPlot->xAxis->pixelToCoord(ChickedPoint.x()); double currenty = ui->customPlot->yAxis->pixelToCoord(ChickedPoint.y()); //使用QToolTip輸出值, QToolTip::showText(mapToGlobal(e->pos()),QString("當前點值為:x=%1,y=%2").arg(currentx).arg(currenty),this); }
.h文件
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "ui_mainwindow.h" #include <QMouseEvent> #define PI 3.1415926 namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); //設置一容器 double num[20]; double n=0; void graph_show(QCustomPlot *customPlot); public slots: void graph_show(); void mouseReleaseEvent(QMouseEvent *e); // void mouseMoveEvent(QMouseEvent *e); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
靜態曲線的命名方法可以選用:
customPlot->legend->setVisible(true); customPlot->graph(0)->setName("sin");
此處是對第一條曲線進行命名為“sin“。