//在项目中添加qcustomplot.h 与 qcustomplot.cpp,并在.pro文件中添加QT += widgets printsupport 这是因为qcustomplot基于图片输出功能
//头文件定义了QCustomPlot *m_QcustomPlot;
//头文件包含了#include “qcustomplot.h”
qcustomplot类CSDN下载链接
qcustomplot类官网下载地址
#include "mainwindow.h"
#include <QLayout>
#include <QVector>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
m_QcustomPlot = new QCustomPlot;
//也可先用widget布局好后再加入
setCentralWidget(m_QcustomPlot);
//设置样式,拖拽、缩小、是否可选中
m_QcustomPlot->setInteractions(QCP::iRangeDrag/*拖拽*/ | QCP::iRangeZoom/*缩小*/ | QCP::iSelectAxes |QCP::iSelectLegend | QCP::iSelectPlottables);
m_QcustomPlot->axisRect()->setupFullAxesBox(false);//设置四周全轴框
m_QcustomPlot->addGraph(); //添加曲线,每加入一条曲线需调用一次
QVector<double> vecX, vecY;//横坐标值、纵坐标值
vecX<<1<<2<<3<<4<<15;
vecY<<1.3<<2<<3.1<<3.5<<6;
m_QcustomPlot->graph(0)->setData(vecX, vecY);//在第一个权限中添加数据点
//动态加点
m_QcustomPlot->graph(0)->addData(19.7, 2.11);
//设置标题, 必须先调用insertRow插入一行才能够显示
m_QcustomPlot->plotLayout()->insertRow(0);
QCPTextElement *title = new QCPTextElement(m_QcustomPlot, "身高体重标准对照表", QFont("sans", 17, QFont::Bold));
m_QcustomPlot->plotLayout()->addElement(0, 0, title);
//设置颜色、线宽
QPen graphPen;
graphPen.setColor(QColor(rand()%245+10, rand()%245+10, rand()%245+10));//QColor::yellow()
graphPen.setWidthF(rand()/(double)RAND_MAX*2+1);
m_QcustomPlot->graph(0)->setPen(graphPen);
//显示线介绍,默认右上角
m_QcustomPlot->legend->setVisible(true);
QFont legendFont = font();
legendFont.setPointSize(10);
m_QcustomPlot->legend->setFont(legendFont);
m_QcustomPlot->legend->setSelectedFont(legendFont);
m_QcustomPlot->legend->setSelectableParts(QCPLegend::spItems); // legend box shall not be selectable, only legend items
//设置坐标名
m_QcustomPlot->xAxis->setLabel("x 身高");
m_QcustomPlot->yAxis->setLabel("y 体重");
//重新调节轴、调用后坐标会根据实际情况增加
m_QcustomPlot->rescaleAxes();
//重新生成图表
m_QcustomPlot->replot();
}
******************
MainWindow::~MainWindow()
{
}