Search code examples
pythonpyqt5pyside2

Why after zooming qraphicsview qraphicsitem leaves traces


When moving objects in zoomed mode, objects start to leave traces, but in normal mode everything works perfectly. I thought it was a bouldingRect, however one of my questions provides a normal implementation.

example

my MRE is in this question My last question


Solution

  • This is due to the painting of the outline, that always occupies half of the pen width if it draws on the borders. As the documentation about boundingRect() explains:

    Note: For shapes that paint an outline / stroke, it is important to include half the pen width in the bounding rect. It is not necessary to compensate for antialiasing, though.

    Since in your case you specified the pen width in the init, you can use that value:

        def boundingRect(self):
            return QRectF(
                -self.penWidth / 2, 
                -self.penWidth / 2, 
                self.w + self.penWidth, 
                self.h + self.penWidth)
    

    Please note that you actually are not using that pen in the painter, so a more correct implementation should be done using painter.setPen(QtGui.QPen(self.pen_color, self.penWidth)) in the paint() function. To slightly improve performance, create a QPen in the init and use that directly for setPen().

    Also note that every setting that is changed within the painter (including pen and brush) should not be persistent, so it's always good practice remember to put a qp.save() at the beginning of the paint() and qp.restore() before returning.