Search code examples
pythonpyside2

Qt fails to paint multiple QRect on widget


I have a simple code in PySide2 to paint multiple QRects (20 red QRect) on the screen. Running the code it only paints a single (the last) instance of these QRects. What I am doing wrong?

def paintEvent(self, event:QPaintEvent):

    if self.cell != None:
        painter = QPainter(self)
        painter.setPen(Qt.NoPen)
        painter.setBrush(Qt.red)
        painter.drawRect(self.cell)

def drawBoard(self):

    cellWidth =  self.width / self.columns
    cellHeight = self.height / self.rows

    for r in range(0, self.rows):
        for c in range(0, self.columns):

            if (self.grid[r][c]):
                # this gets executed 20 times

                cellx = cellWidth * c
                celly = cellHeight * r
                self.cell = QRect(cellx, celly, cellWidth, cellHeight)

                # paint cell on widget
                self.update()

How do I call the paintEvent to paint multiple instances on the widget?


Solution

  • Unless told otherwise Qt will generally erase/fill the background of a QWidget before invoking the paintEvent method -- that's why you only see the last rectangle.

    Try moving the paint logic into paintEvent itself (untested)...

    def paintEvent(self, event:QPaintEvent):
        if self.cell != None:
            painter = QPainter(self)
            painter.setPen(Qt.NoPen)
            painter.setBrush(Qt.red)
            cellWidth =  self.width / self.columns
            cellHeight = self.height / self.rows
            for r in range(0, self.rows):
                for c in range(0, self.columns):
                    if (self.grid[r][c]):
                        # this gets executed 20 times
    
                        cellx = cellWidth * c
                        celly = cellHeight * r
    
                        # paint cell on widget
                        painter.drawRect(QRect(cellx, celly, cellWidth, cellHeight))
    
    def drawBoard(self):
        self.update()