1. 显示图像,按鼠标所在位置为中心进行放大缩小(当出现滚动条的时候)
methold 1 ? 一开始还有效,后来加了其他东西,不能用了 原因为查
class MyView : public QGraphicsView
void MyView::wheelEvent(QWheelEvent *event) //滚轮事件
{
setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
if(event->delta() > 0) //如果鼠标滚轮远离使用者,则delta()返回正值
scale(1.2,1.2); //视图缩放
else scale(0.83,0.83);
}
methold 2 测试ok
void MyView::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();
int wheelDeltaValue = event->delta();
// 向上滚动,放大;
if (wheelDeltaValue > 0)
{
this->scale(1.2, 1.2);
}
// 向下滚动,缩小;
else
{
this->scale(1.0 / 1.2, 1.0 / 1.2);
}
// 将scene坐标转换为放大缩小后的坐标;
QPointF viewPoint = this->matrix().map(scenePos);
// 通过滚动条控制view放大缩小后的展示scene的位置;
horizontalScrollBar()->setValue(int(viewPoint.x() - viewWidth * hScale));
verticalScrollBar()->setValue(int(viewPoint.y() - viewHeight * vScale));
}
2. 去掉滚动条
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);