QGraphicsPathItem 上的 QPropertyAnimation

问题描述

我正在尝试为 QGraphicsPathItem 的颜色设置动画。在 Qt 文档中,他们说如果您将要设置动画的项目子类化,则可以为 QGraphicsItem 设置动画。这是 Qt 文档所说的(来自 Animations and the Graphics View Framework):

当您想为 QGraphicsItems 设置动画时,您还可以使用 QPropertyAnimation。但是,QGraphicsItem 不继承 QObject。一种 好的解决方案是将您希望动画的图形项目子类化。 这个类也将继承 QObject。这条路, QPropertyAnimation 可用于 QGraphicsItems。下面的例子 显示这是如何完成的。另一种可能是继承 QGraphicsWidget,它已经是一个 QObject。

注意 QObject 必须是作为元对象继承的第一个类 系统要求这样做。

我尝试这样做,但由于这个原因,我的程序在创建新的“Edge”类时崩溃了。

带有 QObject 的我的 Edge 类:

class Edge(QObject,QGraphicsPathItem):

    def __init__(self,point1,point2):
        super().__init__()
        self.point1 = point1
        self.point2 = point2
        self.setPen(QPen(Qt.white,2,Qt.solidLine))

    def create_path(self,radius):
        path = QPainterPath()
        path.moveto(self.point1.x() + radius,self.point1.y() + radius)
        path.lineto(self.point2.x() + radius,self.point2.y() + radius)

        return path

解决方法

QObject 继承的概念不适用于 python,因为多重继承仅在某些情况下可用,而 QGraphicsItem 则不是这种情况。一种可能的解决方案是使用 QVariantAnimation 的组合来实现动画。

class Edge(QGraphicsPathItem):
    def __init__(self,point1,point2):
        super().__init__()
        self.point1 = point1
        self.point2 = point2
        self.setPen(QPen(Qt.white,2,Qt.SolidLine))

        self.animation = QVariantAnimation()
        self.animation.valueChanged.connect(self.handle_valueChanged)
        self.animation.setStartValue(QColor("blue"))
        self.animation.setEndValue(QColor("red"))
        self.animation.setDuration(1000)

    def create_path(self,radius):
        path = QPainterPath()
        path.moveTo(self.point1.x() + radius,self.point1.y() + radius)
        path.lineTo(self.point2.x() + radius,self.point2.y() + radius)
        return path

    def start_animation(self):
        self.animation.start()

    def handle_valueChanged(self,value):
        self.setPen(QPen(value),Qt.SolidLine)