我找不到将鼠标事件附加到场景的方法。如果没有View,所有事件都会被捕获,但是当注释掉时,只有mousePressEvent可以工作。请帮忙。
from PySide import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.Scene()
self.View()
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
print "Pressed!!!"
def mouseMoveEvent(self, event):
print "moving....."
def mouseReleaseEvent(self, event):
print "-------released"
def Scene(self):
self.s = QtGui.QGraphicsScene(self)
def View(self):
self.v = QtGui.QGraphicsView(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_())
答案 0 :(得分:4)
在Qt中,事件从子到父处理。首先,孩子得到了这个事件。然后它决定它是否会处理事件。如果它不想对它采取行动,它可以ignore
事件和事件将被传递给父母。
在您的设置中,您有QMainWindow
作为父级,QGraphicsView
作为其子级。 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
会收到活动并对其采取行动。