pyqt QGraphicsView 以鼠標為中心進行縮放功能實現(xiàn)
注意幾個關(guān)鍵點:
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. 關(guān)鍵實現(xiàn)函數(shù):重定義滾輪縮放事件(可能會達不到預(yù)期效果,請看步驟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 #按需調(diào)整
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. 如果未到達預(yù)期效果,可能還需重寫所有鼠標事件:
def mousePressEvent(self, event: QMouseEvent) -> None:
if event.button() == Qt.LeftButton:
self.dragStartPos = event.pos() #用于鼠標拖拽視圖
returndef mouseReleaseEvent(self, event: QMouseEvent) -> None:
pass
returndef mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton: # 實現(xiàn)鼠標拖拽視圖
newpos = event.pos()
delta = newpos - self.dragStartPos
self.dragStartPos = newpos
self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y())
self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x())
return僅此記錄,未重定義鼠標所有事件導致了近半個月的苦惱,雖然修復了但是仍不知道什么原因
到此這篇關(guān)于pyqt QGraphicsView 以鼠標為中心進行縮放的文章就介紹到這了,更多相關(guān)pyqt QGraphicsView 鼠標縮放內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python之tkinter進度條Progressbar用法解讀
這篇文章主要介紹了Python之tkinter進度條Progressbar用法解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
pytorch 實現(xiàn)計算 kl散度 F.kl_div()
這篇文章主要介紹了pytorch 實現(xiàn)計算 kl散度 F.kl_div(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
在Python 3中緩存Exception對象會造成什么后果?
這篇文章主要介紹了在Python 3中緩存Exception對象到底會造成什么后果?下面帶著這個問題一起看看文章的解析,需要的朋友可以參考一下2021-12-12
Python如何調(diào)用spire.doc輕松讀取Word文檔內(nèi)容
Spire.Doc?for?.NET?是一款專門對?Word?文檔進行操作的?.NET?類庫,本文為大家介紹了Python如何調(diào)用spire.doc實現(xiàn)輕松讀取Word文檔內(nèi)容,需要的可以了解下2025-02-02

