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