0

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
ytobi
  • 535
  • 1
  • 9
  • 19

1 Answers1

1

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()
G.M.
  • 12,232
  • 2
  • 15
  • 18
  • This works, but I like to paint the widget at other times, how do I do this without losing the previous paint? like moving a QRect around in the grid. – ytobi Oct 21 '19 at 20:43
  • 1
    Then you need to make your class stateful -- it needs to maintain a list of the rectangles it should draw whenever `paintEvent` is invoked. – G.M. Oct 21 '19 at 20:53
  • Slipped my mind. I think you can include that in the answer in case it helps someone in the future. – ytobi Oct 21 '19 at 20:56