Search code examples
pythonpyqtpyqt5qgraphicssceneqgraphicsitem

custom QGraphicsItem not moving properly


I tried to customize QGraphicsItem to make a pawn item that will be movable but will be centered on a case when dropped (modeling a checkers or chess board)

i encountered a problem at the very start as my custom graphic item does not move properly, when dragged it leaves a trail and the object disappear

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,
                         QGraphicsView, QGraphicsScene, QGraphicsItem)
from PyQt5.QtGui import QPen, QBrush, QTransform
from PyQt5.QtCore import Qt, QRectF, QPointF

class Pawn(QGraphicsItem):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.setFlag(QGraphicsItem.ItemIsMovable)

    def paint(self, painter, options, widget):
        painter.drawEllipse(0, 0, 30, 30)

    def boundingRect(self):
        return QRectF(self.x() - 10, self.y() - 10, 50, 50)


class MainWin(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        scene = QGraphicsScene()
        view = QGraphicsView(scene, self)
        view.setGeometry(0, 0, 290, 290)

        ellipse = scene.addEllipse(200, 200, 20, 20, QPen(Qt.yellow), QBrush(Qt.yellow))
        custom = Pawn()
        scene.addItem(custom)

        ellipse.setFlag(QGraphicsItem.ItemIsMovable)

        self.setWindowTitle('doodling')
        self.setGeometry(200, 200, 300, 300)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWin()
    sys.exit(app.exec_())

Solution

  • The boundingRect() is a rectangle that is used to indicate the area where it should be painted, and this area is with respect to the item's coordinate system, and not the scene's coordinate system, so you should not use x() or y() since they are measured with respect to the coordinates of the scene.

    def boundingRect(self):
        return QRectF(-10, -10, 50, 50)
    

    See Graphics View Framework for more information