有人可以告诉我以下代码有什么问题吗?我想通过 QGraphicsView 项目上的事件过滤器传递鼠标点击。我读到事件过滤器应该安装到视口,所以在这段代码的情况下,这将是 self._scene 变量。但是,在我的示例中,事件过滤器被忽略,并且 mousePressEvent 事件每次都会被触发而不会被拦截。
非常欢迎任何帮助,感谢您的阅读。
from PyQt6 import QtWidgets
from PyQt6.QtCore import QEvent, Qt
class display(QtWidgets.QGraphicsView):
def __init__(self, parent):
super(display, self).__init__(parent)
self._scene = QtWidgets.QGraphicsScene(self)
self.setScene(self._scene)
self._scene.installEventFilter(self)
def eventFilter(self, QObject, event):
if event.type() == QEvent.Type.MouseButtonPress:
if event.button() == Qt.MouseButton.RightButton:
print("Right button intercepted")
if event.button() == Qt.MouseButton.LeftButton:
print("left button intercepted")
return True
def mousePressEvent(self, event):
print("I clicked the mouse ")
super(display, self).mousePressEvent(event)
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.viewer = display(self) # Call class
VBlayout = QtWidgets.QVBoxLayout(self)
VBlayout.addWidget(self.viewer)
self.setLayout(VBlayout)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 800, 600)
window.show()
sys.exit(app.exec())
答案是 QEvent.Type.GraphicsSceneMousePress 而不是 QEvent.Type.MouseButtonPress:希望它对其他人有帮助