????????以PySide(PyQt)的圖片項為例,比如一個視窗的場景底圖是一個QGraphicsPixmapItem,需要修改它的鼠標滾輪事件,以實現鼠標滾輪縮放顯示的功能。為了達到這個目的,可以重新定義一個QGraphicsPixmapItem類,并重寫它的wheelEvent()函數:
class MyGraphicsPixmapItem(QGraphicsPixmapItem):def __init__(self, pixmap):super().__init__(pixmap)def wheelEvent(self, event):self.setScale(self.scale() * (1.001 ** event.delta()))
然后在代碼中實例化這個類就可以了,這沒有任何問題。
????????需求的提出:
????????首先,場景中只有這一個場景底圖,而且我僅僅只需要修改它的鼠標滾輪事件響應這個函數,為了這簡單的一個需求重建一個新的類,不是那么優雅。然后,鼠標滾輪縮放顯示的這個功能,我還想用到別的目標上,需要復用和方便移植。或者,鼠標滾輪的事件響應,我需要在程序中根據工況不同動態改變。為此,可以采用types.MethodType動態定義事件方法:
from PySide6.QtCore import Qt
from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import QGraphicsScene, QGraphicsView, QApplication, QGraphicsPixmapItem, QGraphicsItem, \QGraphicsRectItem
import typesapp = QApplication([])# 鼠標滾輪縮放的功能(附加檢測shift鍵縮放)
def wheelZoom(graphics_item, event):if event.modifiers() & Qt.ShiftModifier:graphics_item.setScale(graphics_item.scale() * (1.001 ** event.delta()))# ############不檢測shift鍵縮放###############
# def wheelZoom(graphics_item, event):
# graphics_item.setScale(graphics_item.scale() * (1.001 ** event.delta()))
# ##########################################
def hover_enter_event(graphics_item, event):print("鼠標進入")event.accept()def hover_leave_event(graphics_item, event):print("鼠標離開")event.accept()scene = QGraphicsScene() # 創建場景對象
view = QGraphicsView(scene) # 創建視圖對象# 設置場景并顯示
view.setScene(scene)
view.show()
pixmap = QPixmap("example.jpg") # 加載圖片
pixmap_item = QGraphicsPixmapItem(pixmap) # 創建圖片對象
scene.addItem(pixmap_item) # 將圖片添加到場景中rect_item = QGraphicsRectItem(100,100,100,100) # 創建一個矩形對象
scene.addItem(rect_item) # 將矩形添加到場景中pixmap_item.setAcceptHoverEvents(True) # 設置圖片接受鼠標事件
pixmap_item.wheelEvent = types.MethodType(wheelZoom, pixmap_item) # 給圖像項添加滾輪縮放事件
rect_item.wheelEvent = types.MethodType(wheelZoom, rect_item) # 給圖像項添加滾輪縮放事件
pixmap_item.hoverEnterEvent = types.MethodType(hover_enter_event, pixmap_item) # 給圖像項添加鼠標進入事件
pixmap_item.hoverLeaveEvent = types.MethodType(hover_leave_event, pixmap_item) # 給圖像項添加鼠標離開事件app.exec()
上面的代碼,定義了幾個方法,并且將其動態綁定到了圖片項的實例,實現了所需的功能。
types的更多學習筆記見:Python的types庫學習記錄-CSDN博客