当我使用滚轮缩放图像时,将始终以锚点在左上角的方式缩放图像。
但是当我注释掉 mouseMoveEvent 函数时,可以使用鼠标位置作为锚点缩放图像。
这是我的代码:
class myQGraphicsView(QGraphicsView):
def __init__(self, *__args):
super().__init__(*__args)
self.setTransformationAnchor(self.AnchorUnderMouse)
self.pressed = 0
self.setMouseTracking(False)
def mousePressEvent(self, QMouseEvent):
print(1)
self.pressed = 1
self.last_mouse_x = QMouseEvent.x()
self.last_mouse_y = QMouseEvent.y()
def mouseMoveEvent(self, QMouseEvent):
if self.pressed == 1:
self.current_mouse_x = QMouseEvent.x()
self.current_mouse_y = QMouseEvent.y()
self.horizontalScrollBar().setValue(
self.horizontalScrollBar().value() -(self.current_mouse_x - self.last_mouse_x))
self.verticalScrollBar().setValue(
self.verticalScrollBar().value() - (self.current_mouse_y - self.last_mouse_y))
# print(self.current_mouse_x - self.last_mouse_x, self.current_mouse_y - self.last_mouse_y)
# self.img_view.translate(self.current_mouse_x - self.last_mouse_x, self.current_mouse_y - self.last_mouse_y)
# self.img_view.translate(1, 1)
self.last_mouse_x = self.current_mouse_x
self.last_mouse_y = self.current_mouse_y
def mouseReleaseEvent(self, QMouseEvent):
self.pressed = 0
def wheelEvent(self, QWheelEvent):
if QApplication.keyboardModifiers() == Qt.ControlModifier:
print(self.mapToScene(self.x(), self.y()))
angle = QWheelEvent.angleDelta().y()
if angle > 0:
scale_factor = 1.25
else:
scale_factor = 0.8
self.scale(scale_factor, scale_factor)
ui_1.current_img_w = ui_1.current_img_w * scale_factor
ui_1.current_img_h = ui_1.current_img_h * scale_factor