QGraphicsPathItem上的QPropertyAnimation

2024-09-28 17:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

When you want to animate QGraphicsItems, you also use QPropertyAnimation. However, QGraphicsItem does not inherit QObject. A good solution is to subclass the graphics item you wish to animate. This class will then also inherit QObject. This way, QPropertyAnimation can be used for QGraphicsItems. The example below shows how this is done. Another possibility is to inherit QGraphicsWidget, which already is a QObject.

Note that QObject must be the first class inherited as the meta-object system demands this.

我试图这样做,但由于这个原因,当我的程序创建一个新的“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

Tags: thetopathselfyouis动画qt
1条回答
网友
1楼 · 发布于 2024-09-28 17:29:57

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), 2, Qt.SolidLine)

相关问题 更多 >