PySide(PyQt),使用types.MethodType动态定义事件

打印 上一主题 下一主题

主题 924|帖子 924|积分 2772

        以PySide(PyQt)的图片项为例,好比一个视窗的场景底图是一个QGraphicsPixmapItem,必要修改它的鼠标滚轮事件,以实现鼠标滚轮缩放表现的功能。为了达到这个目的,可以重新定义一个QGraphicsPixmapItem类,并重写它的wheelEvent()函数:
  1. class MyGraphicsPixmapItem(QGraphicsPixmapItem):
  2.     def __init__(self, pixmap):
  3.         super().__init__(pixmap)
  4.         
  5.     def wheelEvent(self, event):
  6.         self.setScale(self.scale() * (1.001 ** event.delta()))
复制代码
然后在代码中实例化这个类就可以了,这没有任何问题。
        需求的提出:

        起首,场景中只有这一个场景底图,而且我仅仅只必要修改它的鼠标滚轮事件响应这个函数,为了这简单的一个需求重建一个新的类,不是那么优雅。然后,鼠标滚轮缩放表现的这个功能,我还想用到别的目标上,必要复用和方便移植。大概,鼠标滚轮的事件响应,我必要在步伐中根据工况不同动态改变。为此,可以接纳types.MethodType动态定义事件方法:
  1. from PySide6.QtCore import Qt
  2. from PySide6.QtGui import QPixmap
  3. from PySide6.QtWidgets import QGraphicsScene, QGraphicsView, QApplication, QGraphicsPixmapItem, QGraphicsItem, \
  4.     QGraphicsRectItem
  5. import types
  6. app = QApplication([])
  7. # 鼠标滚轮缩放的功能(附加检测shift键缩放)
  8. def wheelZoom(graphics_item, event):
  9.     if event.modifiers() & Qt.ShiftModifier:
  10.         graphics_item.setScale(graphics_item.scale() * (1.001 ** event.delta()))
  11. # ############不检测shift键缩放###############
  12. # def wheelZoom(graphics_item, event):
  13. #     graphics_item.setScale(graphics_item.scale() * (1.001 ** event.delta()))
  14. # ##########################################
  15. def hover_enter_event(graphics_item, event):
  16.     print("鼠标进入")
  17.     event.accept()
  18. def hover_leave_event(graphics_item, event):
  19.     print("鼠标离开")
  20.     event.accept()
  21. scene = QGraphicsScene()  # 创建场景对象
  22. view = QGraphicsView(scene)  # 创建视图对象
  23. # 设置场景并显示
  24. view.setScene(scene)
  25. view.show()
  26. pixmap = QPixmap("example.jpg")  # 加载图片
  27. pixmap_item = QGraphicsPixmapItem(pixmap)  # 创建图片对象
  28. scene.addItem(pixmap_item)  # 将图片添加到场景中
  29. rect_item = QGraphicsRectItem(100,100,100,100)  # 创建一个矩形对象
  30. scene.addItem(rect_item)  # 将矩形添加到场景中
  31. pixmap_item.setAcceptHoverEvents(True)  # 设置图片接受鼠标事件
  32. pixmap_item.wheelEvent = types.MethodType(wheelZoom, pixmap_item)  # 给图像项添加滚轮缩放事件
  33. rect_item.wheelEvent = types.MethodType(wheelZoom, rect_item)  # 给图像项添加滚轮缩放事件
  34. pixmap_item.hoverEnterEvent = types.MethodType(hover_enter_event, pixmap_item)  # 给图像项添加鼠标进入事件
  35. pixmap_item.hoverLeaveEvent = types.MethodType(hover_leave_event, pixmap_item)  # 给图像项添加鼠标离开事件
  36. app.exec()
复制代码
  1. 上面的代码,定义了几个方法,并且将其动态绑定到了图片项的实例,实现了所需的功能。
复制代码

types的更多学习条记见:Python的types库学习记录-CSDN博客

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

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

惊雷无声

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表