【问题标题】:QPropertyAnimation on QGraphicsPathItemQGraphicsPathItem 上的 QPropertyAnimation
【发布时间】:2021-07-02 13:56:30
【问题描述】:

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

当你想为 QGraphicsItems 设置动画时,你也可以使用 QProperty动画。但是,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

【问题讨论】:

  • PyQt 不适用于 Qt 对象的多重继承 - 它通常会失败或导致程序挂起。如果您需要使用该项目的 属性,请将 QGraphicsObject 子类化并将 QGraphicsPathItem 添加为其子 item(您可以创建一个 pyqtProperty() 用作 getter/setter项),否则使用简单的 QVariantAnimation。

标签: python inheritance pyqt5 qgraphicsitem qobject


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 2019-04-17
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多