pyqt QGraphicsView 以鼠標(biāo)為中心進(jìn)行縮放功能實(shí)現(xiàn)
注意幾個關(guān)鍵點(diǎ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)鍵實(shí)現(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)拖拽視圖
returndef mouseReleaseEvent(self, event: QMouseEvent) -> None:
pass
returndef mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton: # 實(shí)現(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使用for循環(huán)遍歷字符串列表字典的操作流程
本文介紹了for循環(huán)遍歷字符串列表字典在Python中的重要性、應(yīng)用場景、技術(shù)原理、實(shí)踐應(yīng)用、常見問題及解決方案和最佳實(shí)踐等內(nèi)容,旨在幫助讀者掌握for循環(huán)遍歷的基本用法和提高編程效率,需要的朋友可以參考下2026-05-05
Python二叉樹的鏡像轉(zhuǎn)換實(shí)現(xiàn)方法示例
這篇文章主要介紹了Python二叉樹的鏡像轉(zhuǎn)換實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了二叉樹鏡像轉(zhuǎn)換的原理及Python相關(guān)算法實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-03-03
在主機(jī)商的共享服務(wù)器上部署Django站點(diǎn)的方法
這篇文章主要介紹了在主機(jī)商的共享服務(wù)器上部署Django站點(diǎn)的方法,Django是最具人氣的Python框架,需要的朋友可以參考下2015-07-07
分析解決Python中sqlalchemy數(shù)據(jù)庫連接池QueuePool異常
這篇文章主要來給大家分析sqlalchemy數(shù)據(jù)庫連接池QueuePool的異常,給大家用詳細(xì)的圖文方式做出了解決的方案,有需要的朋友可以借鑒參考下,希望可以有所幫助2021-09-09

