问题
使用QwtPlotMagnifier时,用滚轮缩放时,缩放中心是QwtPlot的中间。
现需要改成在鼠标中间进行缩放
功能预览
更改
- 创建MyPlotMagnifier,并继承QwtPlotMagnifier
- 重写rescale函数,将源码中的rescale复制
- 修改如下部分
void MyPlotMagnifier::rescale( double factor )
{
QwtPlot* plt = plot();
if ( plt == NULL )
return;
factor = qAbs( factor );
if ( factor == 1.0 || factor == 0.0 )
return;
bool doReplot = false;
const bool autoReplot = plt->autoReplot();
plt->setAutoReplot( false );
//添加
QPoint cursorPos = canvas()->mapFromGlobal(canvas()->cursor().pos());
for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
{
if ( isAxisEnabled( axisId ) )
{
const QwtScaleMap scaleMap = plt->canvasMap( axisId );
double v1 = scaleMap.s1();
double v2 = scaleMap.s2();
if ( scaleMap.transformation() )
{
// the coordinate system of the paint device is always linear
v1 = scaleMap.transform( v1 ); // scaleMap.p1()
v2 = scaleMap.transform( v2 ); // scaleMap.p2()
}
//源码里的
// const double center = 0.5 * ( v1 + v2 );
// const double width_2 = 0.5 * ( v2 - v1 ) * factor;
// v1 = center - width_2;
// v2 = center + width_2;
// qDebug()<<axisId<<center<<v1<<v2;
//需要改成
const double posInAxis = (axisId/2?cursorPos.x():cursorPos.y());
const double lenthInAxis = (axisId/2?canvas()->rect().width():canvas()->rect().height());
double posRadio = posInAxis / lenthInAxis;//获取当前鼠标在X/Y轴的位置(百分比)
if(axisId/2 == 0)//plot的Y轴方向与鼠标Y轴方向不同
{
posRadio = 1-posRadio;
}
double center = posRadio * ( v2 - v1 ) + v1;//将百分比转化为v1到v2的点
v1 = center - (center-v1) * factor;//将鼠标中心分成两部分,分别进行缩放
v2 = center + (v2 - center) * factor;
if ( scaleMap.transformation() )
{
v1 = scaleMap.invTransform( v1 );
v2 = scaleMap.invTransform( v2 );
}
plt->setAxisScale( axisId, v1, v2 );
doReplot = true;
}
}
plt->setAutoReplot( autoReplot );
if ( doReplot )
plt->replot();
}
``