Pay attention to several key points:
1. Initialization
class CustomGraphicsView(QGraphicsView): def __init__(self, parent=None): super(CustomGraphicsView, self).__init__(parent) = QGraphicsScene() () (0, 0, 1024, 600) # The following initialization code is more important (True) () # Turn on as needed # () # Open as needed () ()
2. Key implementation function: Redefine the scroll wheel scaling event (the expected effect may not be achieved, please see step 3 or confirm the initialization)
def wheelEvent(self, event: QWheelEvent) -> None: if () == : mouse_pos = () scene_pos = (mouse_pos) #The mouse is in the scene before zooming s = 1.2 #Adjust as needed if(().y() > 0): (s,s) else: (1/s,1/s) view_point = (scene_pos) #After scaling, the original scene maps the new mouse position ().setValue(int(view_point.y()-mouse_pos.y())) #Move the view through the scroll bar ().setValue(int(view_point.x()-mouse_pos.x())) return else: return super().wheelEvent(event) # Ensure that the scroll bar can scroll
3. If the expected effect is not reached, all mouse events may need to be rewrited:
def mousePressEvent(self, event: QMouseEvent) -> None: if () == : = () # Used for mouse drag view return
def mouseReleaseEvent(self, event: QMouseEvent) -> None: pass return
def mouseMoveEvent(self, event): if () and : # Implement mouse drag view newpos = () delta = newpos - = newpos ().setValue(().value() - ()) ().setValue(().value() - ()) return
This record alone, all events of the mouse have not been redefined, which has caused trouble for nearly half a month. Although it has been fixed, I still don’t know why.
This is the end of this article about pyqt QGraphicsView scaling with the mouse as the center. For more related pyqt QGraphicsView, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!