在QCustomPlot第三方库的源文件中找到了qcustomplot.cpp中的 wheelEvent滚轮事件函数。其中原文档说明如下:
/* \internal
Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of the scaling operation is the current cursor position inside the axis rect. The scaling factor is dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of the range zoom factor. This takes care of the wheel direction automatically, by inverting the factor, when the wheel step is negative (f^-1 = 1/f).
*/
大概意思是:如果rangeZoom设置为Qt::Horizontal,Qt::Vertical或者两个都是,那么坐标轴的范围用定义为rangeZoomHorzAxis和rangeZoomVertAxis来进行缩放。缩放操作的中心是axis rect里的当前光标位置。缩放因子取决于鼠标滚轮增量(滚轮旋转的方向)用来提供自然的缩放效果。缩放的强度可以通过setRangeZoomFactor来控制。
注意,对于单个旋转步长,event->delta()通常为+/-120。但是,如果快速转动鼠标滚轮,许多步长可能会聚集到一个事件,因此event->delta()可能是120的倍数。这里通过计算一个wheelSteps并将其用作范围缩放因子的指数来考虑这一点。当车轮步长为负(f^-1=1/f)时,通过将因子反向,这将自动处理滚轮方向。
那如何实现通过鼠标滚轮缩放图形使yAxis范围总是从零开始呢?
我们不妨自定义一个槽函数setyAxisRange(QCPRange);然后当用鼠标滚轮进行缩放时通过发送范围改变信号rangeChanged(QCPRange),同时触发自定义的槽函数从而实现该功能。
具体代码如下:
在头文件中进行私有槽函数声明:
private slots:
void setyAxisRange(QCPRange);
源程序中进行槽函数实现:
void setyAxisRange(QCPRange)
{
ui->customPlot->yAxis->setRangeLower(0);
}
同时在构造函数中连接信号与槽:
connect(ui->customPlot->yAxis,SIGNAL(rangeChanged(QCPRange)),this,SLOT(setyAxisRange(QCPRange)));
这样无论怎么滚动鼠标滑轮进行缩放图形,yAxis轴的范围不会出现负的情况!