我在PySide2中有一个简单的代码,可以在屏幕上绘制多个QRect(20个红色QRect)。运行代码只会绘制这些QRect的单个(最后一个)实例。我在做什么错了?
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()
如何调用paintEvent在小部件上绘制多个实例?
答案 0 :(得分:1)
除非另有说明,否则Qt
通常会在调用QWidget
方法之前擦除/填充paintEvent
的背景-这就是为什么您只能看到最后一个矩形的原因。
尝试将绘制逻辑本身移至paintEvent
中(未经测试)...
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()