Plotting in Qt

1) First include qcustomplot.h and qcustomplot.cpp in header and source file respectively
2) add printsupport in qt+= expression in  .pro file i.e.,
     QT += core gui serialport printsupport
3) Place a regular QWidget on your form in the desired location. Right click on it and hit Promote to...

In the appearing dialog, enter QCustomPlot in the input field next to Promoted class name. The input next to Header fileshould automatically fill with the correct qcustomplot.h value. Hit Add to add QCustomPlot to the promoted classes list and finally hit Promote to turn the QWidget on your form into a QCustomPlot.


mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->plot->addGraph(); //Graph#0
    ui->plot->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle); //point style in plot
    ui->plot->graph(0)->setLineStyle(QCPGraph::lsNone);  //No line joining points

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addPoint(double x, double y)
{
    qv_x.append(x);
    qv_y.append(y);
}

void MainWindow::clearData()
{
    qv_x.clear();
    qv_y.clear();
}

void MainWindow::plot()
{
    ui->plot->graph(0)->setData(qv_x,qv_y);
    ui->plot->replot();
    ui->plot->update();
}

void MainWindow::on_btn_add_clicked()
{
    addPoint(ui->bx_x->value(), ui->bx_y->value());
    plot();
}

void MainWindow::on_btn_clear_clicked()
{
    clearData();
    plot();
}

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();
    void addPoint(double x, double y);
    void clearData();
    void plot();

private slots:
    void on_btn_add_clicked();

    void on_btn_clear_clicked();

private:
    Ui::MainWindow *ui;

    QVector<double> qv_x, qv_y;
};

#endif // MAINWINDOW_H


Comments

Popular posts from this blog

HackRF with srsLTE and openlte

Blinking a LED in STM32F103C8T6 (Blue Pill) Board

Read Continuously from Serial Port in QT