I can’t find the way to attach mouse events to scene. Without View all events are capcured, but when commented out, only mousePressEvent works. Please, help.
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_())
In Qt, events are handled from child to parent. First the child gets the event. Then it decides whether or not it’ll handle the event. If it doesn’t want to act on it, it can
ignorethe event and the event will be passed to the parent.In your setup, you have
QMainWindowas the parent, and aQGraphicsViewas its child. Every event on theQGraphicsViewwill be handled by theQGraphicsViewfirst. If it doesn’t want the event, it willignoreit and pass on to theQMainWindow.To visualize it better, subclass
QGraphicsViewand override itsmouse*Events:And you’ll see an output like:
As you can see, only the
viewgets to ‘see’ the events, becauseviewdoesn’t choose to pass the events.Alternatively, you can choose to ignore those events in the
QGraphicsView. It’s like saying ‘I don’t do anything with this, let someone else take care of it’. And the event will be passed to the parent for it to choose what to do:And the output:
Now, you can see that
viewgets the event first. But since itignores the event, it’s passed to the main window and only after thatQMainWindowreceives the signal.Long story short, don’t worry. Your
viewwill receive events and act on them just fine.