版权声明:本文为优快云博主“前行中的小猪”的原创文章,遵循CC冲锋队4.0版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/GoForwardToStep/article/details/77035287
void CustomView::wheelEvent(QWheelEvent *event)
{
// 获取当前鼠标相对于view的位置;
QPointF cursorPoint = event->pos();
// 获取当前鼠标相对于scene的位置;
QPointF scenePos = this->mapToScene(QPoint(cursorPoint.x(), cursorPoint.y()));
// 获取view的宽高;
qreal viewWidth = this->viewport()->width();
qreal viewHeight = this->viewport()->height();
// 获取当前鼠标位置相当于view大小的横纵比例;
qreal hScale = cursorPoint.x() / viewWidth;
qreal vScale = cursorPoint.y() / viewHeight;
// 当前放缩倍数;
qreal scaleFactor = this->matrix().m11();
//滚轮的滚动量
QPoint scrollAmount = event->angleDelta();
//正值表示放大,负值表示缩小
scrollAmount.y() > 0 ? zoomIn() : zoomOut();
// 将scene坐标转换为放大缩小后的坐标;
QPointF viewPoint = this->matrix().map(scenePos);
// 通过滚动条控制view放大缩小后的展示scene的位置;
horizontalScrollBar()->setValue(int(viewPoint.x() - viewWidth * hScale));
verticalScrollBar()->setValue(int(viewPoint.y() - viewHeight * vScale));
}
问题的关键在滚动条值的设定上。