QCustomPlot自定义Y轴数字格式

QCustomPlot自定义Y轴数字格式

  • 需求背景
  • 自定义途径
  • 最终效果
  • 题外话

需求背景

某个项目需要显示一长串曲线图,其Y轴坐标范围变化幅度很大,用了默认的配置,由于坐标轴刻度标签长度不一,曲线总体表现得很难看。

自定义途径

QCustomPlot 源码版本是:2.0.1

经过仔细研读QCustomPlot的源码,发现设置标签格式的函数是:

QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
{
  return locale.toString(tick, formatChar.toLatin1(), precision);
}

我需要的标签最长不超过9个字符,所以
源代码之外的配置如下:

    customPlot->yAxis->setNumberFormat("f");
    customPlot->yAxis->setNumberPrecision(3);

同时对上述库函数做了如下修改:

QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
{// 2019-06-28 02:10:22 Mony:修改,最大显示长度为9
  (void)locale;
  return QString("%1").arg(tick,9,formatChar.toLatin1(), precision);
}

最终效果

QCustomPlot自定义Y轴数字格式_第1张图片

题外话

  • 修改Y轴自适应范围的代码
customPlot->yAxis->rescale(true);
  • 修改X轴动态曲线显示的代码(显示范围10分钟)
customPlot->graph(0)->addData(key,value);
customPlot->graph(0)->data().data()->removeBefore(key-600);
customPlot->xAxis->setRange(key-600,key);
customPlot->replot();
  • 改变曲线显示区域的代码
QRect rect = customPlot->viewport();  
rect = rect.adjusted(0,-12,0,12);
customPlot->setViewport(rect);        

改变显示区域的代码,在custom控件大小发生变化的时候,可能会有一些意想不到的问题,上述代码仅适用于控件大小确定的场景。

你可能感兴趣的:(qt)