1、设置基础特性
curveWidget->plotLayout()->insertRow(0); // pCurveWidget、curveWidget为在ui中定义的QCustomPlot对象指针
QString sTitle = tr("实时曲线");
m_pCurvTitle = new QCPTextElement(curveWidget, sTitle);
curveWidget->plotLayout()->addElement(0, 0, m_pCurvTitle); //给坐标设置标题
curveWidget->xAxis->setLabel(tr("相对时间(秒)")); //设置横坐标标题
curveWidget->yAxis->setLabel(tr("幅值")); //设置纵坐标标题
curveWidget->xAxis->setRange(-m_nCurveDataNum, 0); //设置横坐标显示范围
curveWidget->replot();
2、添加曲线
int nCount = m_lstNCurvHar.count();
for (int nIndex = 0; nIndex < nCount; nIndex++)
{
int nHarN = m_lstNCurvHar.at(nIndex);
pCurveWidget->addGraph(pCurveWidget->xAxis, pCurveWidget->yAxis); //添加曲线
QString sHarName = GetHarName(nHarN);
pCurveWidget->graph()->setName(sHarName); //设置曲线名称
QPen graphPen;
graphPen.setColor(QColor(rand()%245+10, rand()%245+10, rand()%245+10));
pCurveWidget->graph()->setPen(graphPen); //设置曲线显示颜色
}
3、设置曲线显示效果
pCurveWidget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes | QCP::iSelectLegend | QCP::iSelectPlottables);
pCurveWidget->legend->setVisible(true);
QFont legendFont = font();
legendFont.setPointSize(10);
pCurveWidget->legend->setBrush(QColor(255,255,255,100)); //图例框背景透明
pCurveWidget->legend->setFont(legendFont); //图例框字体大小
pCurveWidget->legend->setSelectedFont(legendFont);
pCurveWidget->legend->setSelectableParts(QCPLegend::spItems);
int nGraphNum = pCurveWidget->graphCount();
if(nGraphNum > 8) //根据曲线条数设置图例框中曲线图例位置
{
for(int i = 0; i < 5; i++)
{
pCurveWidget->legend->addElement(i,0,pCurveWidget->legend->item(i)); //前五条放在第一列
}
for(int i = 5; i < pCurveWidget->graphCount(); i++)
{
pCurveWidget->legend->addElement(i-5,1,pCurveWidget->legend->item(i)); //后面曲线放在第二列
}
}
4、给曲线添加数据
for (int nIndex = 0; nIndex < nCount; nIndex++) //nCount为添加到坐标中的曲线数目
{
QCPGraph *pGraph = curveWidget->graph(nIndex);
QVector
for (int nArrayID = 0; nArrayID <= nLArrayLast; nArrayID++, i++)
{
x[i] = nArrayID;
y[i] = m_dHarIharAmpVal[nArrayID][nCurvHar-1];
}
pGraph->setData(x,y,true); //给曲线设置数据
}
如果实时刷新曲线数据,则用下面方法添加新数据
pGraph->addData(nNewWaterLevel, m_dHarIharAmpVal[nNewArrayID][nCurvHar-1]);
5、设置曲线显示效果
double dValueDiff = pCurveWidget->yAxis->range().upper - pCurveWidget->yAxis->range().lower;
double dValueMid = (pCurveWidget->yAxis->range().upper + pCurveWidget->yAxis->range().lower) / 2.0;
if (dValueDiff < m_dCurveMinDiff / 5.0) //m_dCurveMinDiff = 0.5,根据曲线值来调整坐标刻度自适应
{
pCurveWidget->yAxis->setRange(dValueMid, dValueDiff * 3.60, Qt::AlignVCenter);
}
else if (dValueDiff < m_dCurveMinDiff)
{
pCurveWidget->yAxis->setRange(dValueMid, dValueDiff * 2.00, Qt::AlignVCenter);
}
else
{
pCurveWidget->yAxis->setRange(dValueMid, dValueDiff * 1.20, Qt::AlignVCenter);
}
pCurveWidget->xAxis->setRange(pCurveWidget->xAxis->range().upper, m_nCurveDataNum, Qt::AlignRight);
以这种方法来设置自适应时,当曲线值恒定时,纵轴刻度会不断增大,需要修改QCustomPlot中的函数rescaleValueAxis(bool onlyEnlarge=false, bool inKeyRange=false),修改地方可参考下图: