一,前言
之前已经完成了小工具的一部分,主要新增的内容是Table表的使用。本次要做的是绘制波形图。
二,需求
使用customplot来绘制波形图,并且可以有示波器计算时间差这样的划线功能。
三,遇到的问题
1. 没有widget UI的界面如何添加customplot?
答:官网介绍的是在UI界面进行widget提升。理解了提升操作对代码的影响后,就可以知道没有ui界面应该如何写代码了。
QWidget *ware = new QWidget;
QCustomPlot *myPlot = new QCustomPlot(ware);
2. 如何实时刷新波形
答:思路是x轴设置为时间坐标,然后启动一个timer周期倒计时。每隔100ms更新数据,重绘一次即可。
void MainWindow::updateDataSlot()
{
double time;
// 获取从1970-0-0到现在的ms值
time = QDateTime::currentMSecsSinceEpoch()/1000.0;
// 添加随机数据到graph
myPlot->graph(0)->addData(time, qrand() % 80 - 5);
#if 1
// 重新设定x轴范围为最近20个时刻,则视图可以动起来
myPlot->xAxis->setRange(time, 20, Qt::AlignRight);
myPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
#else
myPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
// 自动调整坐标最高点和最低点,所以视图可以动起来
myPlot->graph(0)->rescaleAxes();
// 左端点阶梯线样式
myPlot->graph(0)->setLineStyle(QCPGraph::lsStepLeft);
// 显示散点
myPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 5));
#endif
// 重绘
myPlot->replot();
}
3. 如何画竖线打标签?
答:其实类似于游标的思路。我2年前的blog已经写过了,当初专门学习过QCustomPlot一段时间qcustomplot游标测量功能--Apple的学习笔记,所以以前的东西复习下就灵活的用起来了。
void MainWindow::updateDataSlot()
{
int static cnt;
cnt++;
curtime = QDateTime::currentMSecsSinceEpoch()/1000.0;
// 添加数据到graph
myPlot->graph(0)->addData(curtime, qrand() % 80 - 5);
// 设置图形离散值标注的格式,包括点,叉,空心圆,菱形等
myPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDiamond, 3));
if((cnt%40)==0)
{
// 画TAG线
createVLineTag(cnt);
}
// 重新设定x轴范围为最近20个时刻,则视图可以动起来
myPlot->xAxis->setRange(curtime, 20, Qt::AlignRight);
// 重绘
myPlot->replot();
}
void MainWindow::createVLineTag(int val)
{
// 设置游标垂直线
QCPItemStraightLine *m_vline = new QCPItemStraightLine(myPlot);
m_vline->setLayer("overlay");
// 颜色随机
m_vline->setPen(QPen(m_graphColorList[qrand() % 6], 1,Qt::DashLine));
// 超出坐标轴范围则不显示游标线
m_vline->setClipToAxisRect(true);
// 画竖线,x为curtime,y只要0和1即可绘制直线了
m_vline->point1->setCoords(curtime, 0);
m_vline->point2->setCoords(curtime, 1);
// 设置文本框
QCPItemText *m_currentLabel = new QCPItemText(myPlot);
m_currentLabel->setLayer("overlay");
// 超出坐标轴范围则不显示标签
m_currentLabel->setClipToAxisRect(true);
m_currentLabel->setPadding(QMargins(3,3,3,3));
m_currentLabel->setPen(QPen(QColor(130, 130, 130), 0, Qt::DotLine));
m_currentLabel->setBrush(Qt::NoBrush);
// 可以设置显示位置跟随锚点的位置,此次我设置的是绝对位置,添加TAG用的
m_currentLabel->position->setCoords(curtime+0.4,75);
m_currentLabel->setFont(QFont("Arial",8));
m_currentLabel->setColor(Qt::red);
m_currentLabel->setText(QString::number(val));
}
四,效果

五,小结
今天为了我的小工具,复习了下QCustomPlot。不过不是游标的应用了,而是绘制波形,并且打竖线TAG。只要掌握了API,就可以灵活实现各种想要的功能。当我能复用2年前的code的时候,我觉得学习到的东西总有一天会用到,为自己没有虚度年华,感到很开心~
网友评论