Search code examples
pythonqtpyqtqpainter

Why does QPainter clear the widget every time I use it?


I have this code:

def paintEvent(self, paintEvent):
    self._painter.begin(self)
    try:
        while True:
            color, rectangle = self._paint_queue.popleft()
            self._painter.fillRect(rectangle, color)
    except IndexError:
        pass
    finally:
        self._painter.end()

def drawInstruction(self, ptr, instruction):
    rectangle = QtCore.QRect(
             (ptr % self.cols)*CELL_SIZE,
             math.floor(ptr/float(self.cols))*CELL_SIZE,
             CELL_SIZE,
             CELL_SIZE)
    self._paint_queue.append((opcode2color[instruction.opcode],
        rectangle))
    self.update()

And every time I call drawInstruction(), everything that was already drawn is cleared. Only the new rectangle is left.

And repainting everything everytime I call drawInstruction() is not a solution, because drawInstruction() is called very often.


Solution

  • you have to redraw the widget content on each paintEvent, there's no other way.

    maybe in your case it woule be better to draw on a other paint device (QImage, QPixmap, QPicture, ...), and just paint that on each paint event.