QCustomPlot
.h
#ifndef QCUSTOMPLOT_H
#define QCUSTOMPLOT_H
#include <QWidget>
class QCPLayer;
class QCPPainter;
class QCPAxis;
class QCustomPlot: public QWidget
{
Q_OBJECT
public:
explicit QCustomPlot(QWidget *parent = nullptr);
void replot();
public:
QCPLayer *layer(const QString &name) const;
QCPLayer *layer(int index) const;
protected:
virtual void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
virtual void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
virtual void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
virtual void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter);
private:
QList<QCPLayer*> mLayers;
QPixmap mPaintBuffer;
QCPAxis *x1, *x2, *y1, *y2;
};
#endif
.cpp
#include "qcustomplot.h"
#include "qcplayer.h"
#include "qcppainter.h"
#include "qcpaxis.h"
#include <QResizeEvent>
#include <QPainter>
#include <QDebug>
QCustomPlot::QCustomPlot(QWidget *parent) : QWidget(parent),
mPaintBuffer(size())
{
mLayers.append(new QCPLayer(this, QLatin1String("background")));
mLayers.append(new QCPLayer(this, QLatin1String("axes")));
x1 = new QCPAxis(QCPAxis::atBottom, this);
x2 = new QCPAxis(QCPAxis::atTop, this);
y1 = new QCPAxis(QCPAxis::atLeft, this);
y2 = new QCPAxis(QCPAxis::atRight, this);
replot();
}
void QCustomPlot::replot()
{
qDebug() << __FUNCTION__;
mPaintBuffer.fill(Qt::black);
QCPPainter painter;
painter.begin(&mPaintBuffer);
if (painter.isActive()) {
draw(&painter);
painter.end();
}
}
QCPLayer *QCustomPlot::layer(const QString &name) const
{
foreach (QCPLayer *layer, mLayers)
{
if (layer-