pyqt QGraphicsView 以鼠標(biāo)為中心進(jìn)行縮放功能實現(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ù):重定義滾輪縮放事件(可能會達(dá)不到預(yù)期效果,請看步驟3或確認(rèn)初始化)
def wheelEvent(self, event: QWheelEvent) -> None: if event.modifiers() == Qt.ControlModifier: mouse_pos = event.pos() scene_pos = self.mapToScene(mouse_pos) #縮放前鼠標(biāo)在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進(jìn)行映射新鼠標(biāo)位置 self.verticalScrollBar().setValue(int(view_point.y()-mouse_pos.y())) #通過滾動條進(jìn)行移動視圖 self.horizontalScrollBar().setValue(int(view_point.x()-mouse_pos.x())) return else: return super().wheelEvent(event) # 保證滾動條能滾動
3. 如果未到達(dá)預(yù)期效果,可能還需重寫所有鼠標(biāo)事件:
def mousePressEvent(self, event: QMouseEvent) -> None: if event.button() == Qt.LeftButton: self.dragStartPos = event.pos() #用于鼠標(biāo)拖拽視圖 return
def mouseReleaseEvent(self, event: QMouseEvent) -> None: pass return
def mouseMoveEvent(self, event): if event.buttons() and Qt.LeftButton: # 實現(xiàn)鼠標(biāo)拖拽視圖 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
僅此記錄,未重定義鼠標(biāo)所有事件導(dǎo)致了近半個月的苦惱,雖然修復(fù)了但是仍不知道什么原因
到此這篇關(guān)于pyqt QGraphicsView 以鼠標(biāo)為中心進(jìn)行縮放的文章就介紹到這了,更多相關(guān)pyqt QGraphicsView 鼠標(biāo)縮放內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python之tkinter進(jìn)度條Progressbar用法解讀
這篇文章主要介紹了Python之tkinter進(jìn)度條Progressbar用法解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05python二進(jìn)制串轉(zhuǎn)字符串的方法詳解
這篇文章主要介紹了python二進(jìn)制串轉(zhuǎn)字符串的方法詳解,使用json,可以自動檢測編碼,但需要注意的是,它返回的是python對象,不一定是字符串,具體是什么對象要視原始內(nèi)容而定,需要的朋友可以參考下2023-11-11pytorch 實現(xiàn)計算 kl散度 F.kl_div()
這篇文章主要介紹了pytorch 實現(xiàn)計算 kl散度 F.kl_div(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05在Python 3中緩存Exception對象會造成什么后果?
這篇文章主要介紹了在Python 3中緩存Exception對象到底會造成什么后果?下面帶著這個問題一起看看文章的解析,需要的朋友可以參考一下2021-12-12Python如何調(diào)用spire.doc輕松讀取Word文檔內(nèi)容
Spire.Doc?for?.NET?是一款專門對?Word?文檔進(jìn)行操作的?.NET?類庫,本文為大家介紹了Python如何調(diào)用spire.doc實現(xiàn)輕松讀取Word文檔內(nèi)容,需要的可以了解下2025-02-02