PyQt中QGraphicsView内mouseMoveEvent与mouseReleaseEvent无效求助
问题原因
你的Window类中,QGraphicsView组件占满了整个窗口区域,所有鼠标事件都会被QGraphicsView优先接收,导致Window类中重写的mouseMoveEvent和mouseReleaseEvent根本不会被触发。
简单解决方法
不需要用eventFilter,最直接的方式是子类化QGraphicsView,在自定义的视图类中重写鼠标事件方法,这样就能捕获到所有针对视图的鼠标操作。
如果需要在未按住鼠标的情况下也触发mouseMoveEvent,需要给视图开启鼠标追踪(setMouseTracking(True))。
修改后的完整代码
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QGraphicsScene, QGraphicsView class CustomGraphicsView(QGraphicsView): def __init__(self, scene, parent=None): super().__init__(scene, parent) self.setMouseTracking(True) # 可选:开启无按压状态下的鼠标移动追踪 def mousePressEvent(self, event): print('pressed') super().mousePressEvent(event) # 保留父类原有事件处理逻辑,可选 def mouseMoveEvent(self, event): print('moving') super().mouseMoveEvent(event) def mouseReleaseEvent(self, event): print('released') super().mouseReleaseEvent(event) class Window(QWidget): def __init__(self): super().__init__() self.setGeometry(400, 50, 800, 700) scene = QGraphicsScene(-180, -90, 360, 180) # 使用自定义的视图类替代原生QGraphicsView view = CustomGraphicsView(scene) layout = QHBoxLayout(self) layout.addWidget(view) view.scale(1,-1) self.setLayout(layout) if __name__ == '__main__': app = QApplication([]) window = Window() window.show() app.exec()
说明
- 子类化
QGraphicsView后,所有鼠标事件都会先经过自定义类的事件方法,你可以在这里添加自己的业务逻辑,同时通过调用super()保留原有的视图事件处理(比如场景内的元素交互)。 - 如果不需要无按压状态下的鼠标移动追踪,去掉
setMouseTracking(True)即可,此时只有按住鼠标拖动时才会触发mouseMoveEvent。
内容的提问来源于stack exchange,提问作者Abdallah Eldesouky
相关产品推荐
相关产品推荐

