欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > pyqt QGraphicsView 以鼠标为中心进行缩放

pyqt QGraphicsView 以鼠标为中心进行缩放

2024/10/24 21:23:52 来源:https://blog.csdn.net/weixin_44835176/article/details/142468909  浏览:    关键词:pyqt QGraphicsView 以鼠标为中心进行缩放

注意几个关键点:

1. 初始化

class CustomGraphicsView(QGraphicsView):def __init__(self, parent=None):super(CustomGraphicsView, self).__init__(parent)self.scene = QGraphicsScene()self.setScene(self.scene)self.setGeometry(0, 0, 1024, 600)# 以下初始化代码较为重要self.setMouseTracking(True)self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)   # 按需开启# self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)   # 按需开启     self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)

2. 关键实现函数:重定义滚轮缩放事件(可能会达不到预期效果,请看步骤3或确认初始化)

def wheelEvent(self, event: QWheelEvent) -> None:if event.modifiers() == Qt.ControlModifier:mouse_pos = event.pos()scene_pos = self.mapToScene(mouse_pos) #缩放前鼠标在scene的位置s = 1.2 #按需调整if(event.angleDelta().y() > 0):self.scale(s,s)else:self.scale(1/s,1/s)view_point = self.mapFromScene(scene_pos) #缩放后原scene进行映射新鼠标位置self.verticalScrollBar().setValue(int(view_point.y()-mouse_pos.y())) #通过滚动条进行移动视图self.horizontalScrollBar().setValue(int(view_point.x()-mouse_pos.x()))return else:return super().wheelEvent(event) # 保证滚动条能滚动

3. 如果未到达预期效果,可能还需重写所有鼠标事件:

def mousePressEvent(self, event: QMouseEvent) -> None:if event.button() == Qt.LeftButton:self.dragStartPos = event.pos() #用于鼠标拖拽视图return
def mouseReleaseEvent(self, event: QMouseEvent) -> None:passreturn
def mouseMoveEvent(self, event):if event.buttons() and Qt.LeftButton: # 实现鼠标拖拽视图newpos = event.pos()delta = newpos - self.dragStartPosself.dragStartPos = newposself.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y())self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x())return

仅此记录,未重定义鼠标所有事件导致了近半个月的苦恼,虽然修复了但是仍不知道什么原因

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com