问题
I want to report the mouse position whenever I click on a point within a QGraphicsView
widget.
class App(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent)
self.setupUi(self)
self.graphicsView.viewport().installEventFilter(self)
self.graphicsView_2.viewport().installEventFilter(self)
def eventFilter(self, a0: 'QObject', a1: 'QEvent') -> bool:
if a0 == self.graphicsView:
if a1.type() == QtCore.QEvent.MouseButtonPress:
mousePosition = a1.pos()
print(mousePosition.x(), 261 - mousePosition.y())
return True
return False
elif a0 == self.graphicsView_2:
if a1.type() == QtCore.QEvent.MouseButtonPress:
mousePosition = a1.pos()
print(mousePosition.x(), 261 - mousePosition.y())
return True
return False
return False
I only want it to report the mouse button when I press on one of the two QGraphicsView
widgets I have listed. However, with this current code nothing is being triggered at any point. I assume a0
is never equal to the QGraphicsView
widgets I want to compare it to, so I'm unsure how to make this trigger when I want it to.
回答1:
The QGraphicsView inherits from QAbstractScrollArea so the widget you click on is not the QGraphicsView but in its viewport(). And that seems to be understood because you install the event filter in the viewport() so "a0" will never be the QGraphicsView but its viewport(). Also as you compare objects it is better to use "is".
Considering the above, the solution is:
if a0 is self.graphicsView.viewport():
if a0 is self.graphicsView_2.viewport():
来源:https://stackoverflow.com/questions/59148443/pyqt5-event-filter-object-detection