I want to move my SimpleItem object if I move mouse pressing left button. I have successed getting the position of mouse cursor if I press the object. but I have no idea how
In the case of the QGraphicsXXXItem it is not necessary to overwrite any method to enable the movement, it is enough to enable the flag QGraphicsItem::ItemIsMovable.
import sys
from PySide2 import QtGui, QtWidgets, QtCore
class SimpleItem(QtWidgets.QGraphicsItem):
def __init__(self):
QtWidgets.QGraphicsItem.__init__(self)
self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
def boundingRect(self):
penWidth = 1.0
return QtCore.QRectF(-10 - penWidth / 2, -10 - penWidth / 2,
20 + penWidth, 20 + penWidth)
def paint(self, painter, option, widget):
rect = self.boundingRect()
painter.drawRect(rect)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
scene = QtWidgets.QGraphicsScene()
item = SimpleItem()
scene.addItem(item)
view = QtWidgets.QGraphicsView(scene)
view.show()
sys.exit(app.exec_())