如何在PyQt中为绘制的图形添加动画?

4 投票
1 回答
1198 浏览
提问于 2025-04-15 18:49

我已经成功在屏幕上画出了这样的图:

class Window(QWidget):
        #stuff
        graphicsView = QGraphicsView(self)
        scene = QGraphicsScene(self)
        #draw our nodes and edges. 
        for i in range(0, len(MAIN_WORLD.currentMax.tour) - 1):
            node = QGraphicsRectItem(MAIN_WORLD.currentMax.tour[i][0]/3, MAIN_WORLD.currentMax.tour[i][1]/3, 5, 5)
            edge = QGraphicsLineItem(MAIN_WORLD.currentMax.tour[i][0]/3, MAIN_WORLD.currentMax.tour[i][1]/3, 
            MAIN_WORLD.currentMax.tour[i+1][0]/3, MAIN_WORLD.currentMax.tour[i+1][1]/3)
            scene.addItem(node)
            scene.addItem(edge)

        #now go back and draw our connecting edge.  Connects end to home node.
        connectingEdge = QGraphicsLineItem(MAIN_WORLD.currentMax.tour[0][0]/3, MAIN_WORLD.currentMax.tour[0][1]/3,
        MAIN_WORLD.currentMax.tour[len(MAIN_WORLD.currentMax.tour) - 1][0]/3, MAIN_WORLD.currentMax.tour[len(MAIN_WORLD.currentMax.tour) - 1][1]/3)
        scene.addItem(connectingEdge)
        graphicsView.setScene(scene)

        hbox = QVBoxLayout(self)
            #some more stuff..
        hbox.addWidget(graphicsView)

        self.setLayout(hbox)

现在,图中的边缘会不断更新,所以我想要能够删除这些边缘并重新绘制它们。我该怎么做呢?

1 个回答

2

QGraphicsScene 负责管理你添加到场景中的图形元素的绘制。如果你添加的矩形或线条的位置发生了变化,你可以通过保存它们来更新这些位置:

for i in range( ):
    nodes[i] = node = QGraphicsRectItem()
    scene.add(nodes[i])

之后,你可以更新某个节点的位置:

nodes[j].setRect(newx, newy, newwidth, newheight)

线条的更新也是一样的。

如果你需要删除某个元素,可以使用:

scene.removeItem(nodes[22])

撰写回答