Python Qt仍然在QGraphicsItem上调用.paint(),尽管启用了缓存并且没有调用.update()

Python Qt仍然在QGraphicsItem上调用.paint(),尽管启用了缓存并且没有调用.update(),python,qt,graphics,qgraphicsview,Python,Qt,Graphics,Qgraphicsview,我一直试图在Qt PySide中高效地绘制许多“矩形”,但在QGraphicsItem的绘制调用中,它似乎仍然滞后于绘制整个“网格” class GridMapView(QObject, QGraphicsItem): def __init__(self, gridMap, mapWidth, mapHeight, cellSize): QObject.__init__(self) QGraphicsItem.__init__(self) self.setCacheM

我一直试图在Qt PySide中高效地绘制许多“矩形”,但在QGraphicsItem的绘制调用中,它似乎仍然滞后于绘制整个“网格”

class GridMapView(QObject, QGraphicsItem):

def __init__(self, gridMap, mapWidth, mapHeight, cellSize):
    QObject.__init__(self)
    QGraphicsItem.__init__(self)

    self.setCacheMode(QGraphicsItem.ItemCoordinateCache)

    self.gridMap = gridMap
    self.cellSize = cellSize

    self.width = mapWidth
    self.height = mapHeight

    self.setPos(-self.width/2, -self.height/2)

def boundingRect(self):
    return QRectF(0, 0, self.width, self.height)

def paint(self, painter, option, widget):
    painter.setPen(Qt.NoPen)

    unknownBrush = QBrush(QColor('grey'))
    freeBrush = QBrush(QColor('white'))
    occupiedBrush = QBrush(QColor('black'))

    cellRect = QRectF()

    for ix, col in enumerate(self.gridMap):
        for iy, cell in enumerate(col):
            if cell == CellStates.UNKNOWN:
                painter.setBrush(unknownBrush)
            elif cell == CellStates.FREE:
                painter.setBrush(freeBrush)
            elif cell == CellStates.OCCUPIED:
                painter.setBrush(occupiedBrush)

            cellRect.setRect(ix*self.cellSize, iy*self.cellSize, self.cellSize, self.cellSize)
            painter.drawRect(cellRect)
这是渲染几千个矩形,并且滞后很多。设置缓存模式并确保不移动视图似乎没有帮助

我的假设是,如果只在一个单元格更改时重新绘制整个网格,那么在一次过程中绘制整个网格将是有效的

我是不是错过了一些基本的东西?谢谢。

确保在包含该项目场景的视图上设置QGraphicsView.setViewportUpdateModeQGraphicsView.BoundingRectViewportUpdate。在任何一种情况下,当鼠标悬停在GridMapView项目上时,都会调用它的绘制,因此在您的案例中所有的正方形都会重新绘制

另一种实现方式是将每个正方形作为单独的QGraphicsItem,这样,如果在视图上设置了上述视口更新模式,则仅重新绘制需要更新的项目