在 Qt 中,事件是从子级到父级处理的。首先,孩子得到事件。然后它决定是否处理该事件。如果它不想对它采取行动,它可以ignore
事件并且事件将被传递给父级。
在您的设置中,您有QMainWindow
作为父级,aQGraphicsView
作为它的子级。上的每个事件QGraphicsView
都将由第一个处理QGraphicsView
。如果它不想要这个事件,它会ignore
它并传递给QMainWindow
.
为了更好地可视化它,子类化QGraphicsView
并覆盖它mouse*Event
的 s:
from PySide import QtGui, QtCore
class View(QtGui.QGraphicsView):
def mousePressEvent(self, event):
print "QGraphicsView mousePress"
def mouseMoveEvent(self, event):
print "QGraphicsView mouseMove"
def mouseReleaseEvent(self, event):
print "QGraphicsView mouseRelease"
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.Scene()
self.View()
def mousePressEvent(self, event):
print "QMainWindow mousePress"
def mouseMoveEvent(self, event):
print "QMainWindow mouseMove"
def mouseReleaseEvent(self, event):
print "QMainWindow mouseRelease"
def Scene(self):
self.s = QtGui.QGraphicsScene(self)
def View(self):
self.v = View(self.s)
self.setCentralWidget(self.v)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.resize(300, 200)
window.show()
sys.exit(app.exec_())
您会看到如下输出:
QGraphicsView mousePress
QGraphicsView mouseMove
...
QGraphicsView mouseMove
QGraphicsView mouseRelease
如您所见,只有view
“看到”事件,因为view
不选择传递事件。
或者,您可以选择忽略QGraphicsView
. 这就像在说‘我什么都不做,让别人来处理它’。并且该事件将被传递给父级以选择要执行的操作:
class View(QtGui.QGraphicsView):
def mousePressEvent(self, event):
print "QGraphicsView mousePress"
# ignore the event to pass on the parent.
event.ignore()
def mouseMoveEvent(self, event):
print "QGraphicsView mouseMove"
event.ignore()
def mouseReleaseEvent(self, event):
print "QGraphicsView mouseRelease"
event.ignore()
和输出:
QGraphicsView mousePress
QMainWindow mousePress
QGraphicsView mouseMove
QMainWindow mouseMove
...
QGraphicsView mouseMove
QMainWindow mouseMove
QGraphicsView mouseRelease
QMainWindow mouseRelease
现在,您可以看到它view
首先获取事件。但由于它ignore
是事件,它被传递到主窗口,然后才QMainWindow
接收信号。
长话短说,别着急。您view
将收到事件并对其采取行动。