使用QCustomPlot绘制静态曲线。并对常用函数的功能进行说明。
大部分参照别人博客,以在代码工程中附上了链接。
我的学习例程仓库,GitHub:QCustomPlot 学习例程下载
绘图坐标轴布局
坐标轴标签、刻度的分布,如下图示:
基本常用函数
(1)设置坐标轴标签名称 - setLabel
// 给widget绘图控件,设置个别名,方便书写
QCustomPlot *customPlot = ui->widget;
// 设置x,y坐标轴标签名称
customPlot->xAxis->setLabel("x");
customPlot->yAxis->setLabel("y");
(2)设置坐标轴标签颜色 - setLabelColor
// 设置x,y坐标轴标签颜色
customPlot->xAxis->setLabelColor(QColor(0, 160, 230));
customPlot->yAxis->setLabelColor(QColor(0, 160, 230));
(3)设置坐标轴标签字体 - setLabelFont
// 设置x坐标轴标签字体
QFont xFont = customPlot->xAxis->labelFont();
xFont.setPixelSize(20);// 设置像素大小
xFont.setBold(true);// 粗体
xFont.setItalic(true);// 斜体
customPlot->xAxis->setLabelFont(xFont);
(4)设置坐标轴范围 - setRange
// 设置x,y坐标轴显示范围,不设置时默认范围为 0~5
customPlot->xAxis->setRange(-10, 10);
customPlot->yAxis->setRange(-100, 100);
(5)设置坐标轴 主刻度线颜色 - setTickPen
// 设置x,y坐标轴主刻度线颜色
customPlot->xAxis->setTickPen(QPen(Qt::yellow));
customPlot->yAxis->setTickPen(QPen(Qt::yellow));
customPlot->xAxis->setTicks(false);//x轴不显示主刻度
customPlot->yAxis->setTicks(true);//y轴显示主刻度
(6)设置坐标轴 子刻度线颜色 - setSubTickPen
// 设置x,y坐标轴 子刻度线颜色
customPlot->xAxis->setSubTickPen(QColor(255, 165, 0));
customPlot->yAxis->setSubTickPen(QColor(255, 165, 0));
(7)设置坐标轴刻度标签(数字)颜色 - setTickLabelColor
// 设置x,y轴刻度数字颜色
customPlot->xAxis->setTickLabelColor(Qt::white);
customPlot->yAxis->setTickLabelColor(Qt::white);
(8)设置坐标轴基线颜色 - setBasePen
// 设置x,y坐标轴基线颜色
customPlot->xAxis->setBasePen(QPen(Qt::red));
customPlot->yAxis->setBasePen(QPen(Qt::red));
(9)设置背景色 - setBackground
// 设置背景色
customPlot->setBackground(QColor(50, 50, 50));
(10)导出图片 - savePng
// 导出图片
customPlot->savePng("customPlot.png", 480, 320);
导出的图片在 build-xxx-Debug/Release 运行目录下,并非在工程目录下
(11)添加曲线、曲线的坐标点数据
// 添加一条绘图曲线
QCPGraph *pGraph2 = customPlot->addGraph();/// 这行代码等同于 customPlot->addGraph(); QCPGraph *pGraph2 = customPlot->graph(1);
// 设置曲线颜色
pGraph2->setPen(QPen(QColor(0, 0, 255)));
// 曲线的坐标数据,计算x和y的坐标
QVector<double> x1(201), y1(201);
for (int i = 0; i < 201; ++i)
{
x1[i] = -10 + 0.1f *i;
y1[i] = cos(x1[i])*50; // y = 50cosx
}
// 设置曲线的坐标数据
pGraph2->setData(x1, y1);
(12)设置图中单个数据点的连接方式。(有不连接、实现连接、折现、y轴柱状图) - setLineStyle
// 设置图中单个数据点的连接方式
// 帮助手册搜LineStyle可查到相关内容
// lsNone,lsLine(默认的,连线),lsStepLeft,lsStepRight,lsStepCenter,lsImpulse
customPlot->graph(0)->setLineStyle(QCPGraph::lsImpulse);
(13)设置单个数据点的外观(有无散点、散点形状) - setScatterStyle
// 设置每个数据散点为空心圆,大小为5
customPlot->graph()->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
(14)显示图标的图例
// 显示图标的图例
customPlot->legend->setVisible(true);
(15)图表大小自适应曲线数据
customPlot->graph()->rescaleAxes(true);//坐标轴自适应
更多 QCustomPlot控件的使用操作,会在本专栏的后续篇章介绍,一起学习进步。
工程已同步至GitHub,欢迎下载学习。使用时记得遵循GPLv3哦。
我的学习例程仓库,GitHub:QCustomPlot 学习例程下载