以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 types
- app = 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博客
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |