PyQt5 事件过滤器对象检测
PyQt5 Event Filter Object Detection
我想在单击 QGraphicsView
小部件中的某个点时报告鼠标位置。
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
我只希望它在我按下列出的两个 QGraphicsView
小部件之一时报告鼠标按钮。但是,使用此当前代码,任何时候都不会触发任何内容。我假设 a0
永远不会等于我想与之比较的 QGraphicsView
小部件,所以我不确定如何在需要时触发此触发器。
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()
。此外,当您比较对象时,最好使用 "is".
综合以上,解决方案是:
if a0 <b>is</b> self.graphicsView<b>.viewport()</b>:</pre>
if a0 <b>is</b> self.graphicsView_2<b>.viewport()</b>:</pre>
我想在单击 QGraphicsView
小部件中的某个点时报告鼠标位置。
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
我只希望它在我按下列出的两个 QGraphicsView
小部件之一时报告鼠标按钮。但是,使用此当前代码,任何时候都不会触发任何内容。我假设 a0
永远不会等于我想与之比较的 QGraphicsView
小部件,所以我不确定如何在需要时触发此触发器。
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()
。此外,当您比较对象时,最好使用 "is".
综合以上,解决方案是:
if a0 <b>is</b> self.graphicsView<b>.viewport()</b>:</pre>
if a0 <b>is</b> self.graphicsView_2<b>.viewport()</b>:</pre>