Consider this extremely simple example in which you can drag a square around a QGraphicsScene (using PyQt, C++ users read self
as this
)
import sys
from PyQt4 import QtGui, QtCore
class MainWindowUi(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.scene = Scene(0, 0, 300, 300, self)
self.view = QtGui.QGraphicsView()
self.setCentralWidget(self.view)
self.view.setScene(self.scene)
self.scene.addItem(Square(0,0,50,50))
class Scene(QtGui.QGraphicsScene):
def mousePressEvent(self, e):
self.currentItem = self.itemAt(e.pos())
print (self.currentItem)
QtGui.QGraphicsScene.mousePressEvent(self, e)
class Square(QtGui.QGraphicsRectItem):
def __init__(self, *args):
QtGui.QGraphicsRectItem.__init__(self, *args)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = MainWindowUi()
win.show()
sys.exit(app.exec_())
When you click the mouse in the scene you should see a print statement telling you that you clicked either on the square or on nothing (ie. None). This works if you just start the program and click on the square.
Now drag the square away from the upper left corner and click on it again. This time itemAt() return None even when you click on the square.
What's going on?