QT下实时曲线绘制之QCustomPlot
1.QCustomPlot下载:https://www.qcustomplot.com/index.php/download
2.使用这个类不需要添加dll操作,只需把“qcustomplot.h”和“qcustomplot.cpp”两个文件复制到工程目录下。
3.界面设计时拖一个Widget到画图区域,对这个控件->右键“提升为”->QCustomPlot。
此操作后可在界面出现二维坐标系。
4.设置二维线风格。
void LineWidget::setStyle()
{
//添加一条曲线
ui->graphCtrl->addGraph();
QPen pen;
pen.setWidth(2);
//设置画笔颜色
pen.setColor(Qt::blue);
ui->graphCtrl->graph(0)->setPen(pen);
//设置曲线画刷背景
ui->graphCtrl->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20)));
ui->graphCtrl->graph(0)->setAntialiasedFill(false);
//TODO
// ui->graphCtrl->xAxis->setAutoTickStep(false);
// ui->graphCtrl->xAxis->setTickStep(1);
ui->graphCtrl->axisRect()->setupFullAxesBox();
//设置y坐标轴名称
ui->graphCtrl->yAxis->setLabel(QStringLiteral("功率/KW"));
//设置X轴、Y轴范围
ui->graphCtrl->xAxis->setRange(0, 120);
ui->graphCtrl->yAxis->setRange(0, 100);
ui->graphCtrl->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
ui->graphCtrl->graph(0)->setLineStyle((QCPGraph::LineStyle)1);
ui->graphCtrl->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
ui->graphCtrl->xAxis->setTickLabelFont(QFont(QStringLiteral("微软雅黑"),11));
ui->graphCtrl->yAxis->setTickLabelFont(QFont(QStringLiteral("微软雅黑"),11));
ui->graphCtrl->xAxis->setLabelFont(QFont(QStringLiteral("微软雅黑"),12));
ui->graphCtrl->yAxis->setLabelFont(QFont(QStringLiteral("微软雅黑"),12));
connect(ui->graphCtrl->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->graphCtrl->xAxis2, SLOT(setRange(QCPRange)));
connect(ui->graphCtrl->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->graphCtrl->yAxis2, SLOT(setRange(QCPRange)));
}
5.定时器刷新,每秒添加一个数据
mTimer = new QTimer(this);
connect(mTimer, SIGNAL(timeout()), this, SLOT(updateData()));
mTimer->start(1000);
6.添加数据画曲线
void LineWidget::updateData()
{
ui->graphCtrl->graph(0)->addData(mCount-1, mData);
mCount++;//当前点个数
mData++;//新增点的值
if(mCount >= 120)//显示横坐标>120是移动X坐标系
{
ui->graphCtrl->xAxis->setRange(mCount-120, mCount);
}
ui->graphCtrl->replot();
}
效果图: