椭圆动画与QPropertyAnimation的关系

问题描述 投票:-1回答:1

我想对一个椭圆的外观进行动画处理(让它从一个小点变成一个大椭圆)。我读了文档,看了各种例子,但没有任何效果。现在有了下面的代码。

class ellAnimation(QtCore.QObject):
    def __init__(self):
        super(ellAnimation, self).__init__()
        self.mRect = QtCore.QRectF(0, 0, 1, 1)
        self.mItem = QtWidgets.QGraphicsEllipseItem()
        self.mItem.setRect(self.mLine)
        self.mItem.setPen(
            QPen(QColor("black"), 2))

        self.mAnimation = QtCore.QPropertyAnimation(
            self,
            b"rect2",
            parent=self,
            startValue=QtCore.QRectF(0, 0, 1, 1),
            endValue=QtCore.QRectF(0, 0, 500, 500),
            duration=1000,
        )
        self.mAnimation.start()

    def rect1(self):
        return self.mRect.getRect()

    def setRect1(self, rect1):
        self.mRect.setRect(rect1)
        self.mItem.setRect(self.mRect)

    def rect2(self):
        return self.mRect.getRect()

    def setRect2(self, rect2):
        self.mRect.setRect(rect2)
        self.mItem.setRect(self.mRect)

    rect1 = QtCore.pyqtProperty(QtCore.QRectF, fget=rect1, fset=setRect1)
    rect2 = QtCore.pyqtProperty(QtCore.QRectF, fget=rect2, fset=setRect2)

在主代码中,我以这种方式添加到场景中。

animation = ellAnimation() self.scene.addItem(animation.mItem)

这是一个重做线条动画的尝试。帮我重做一下椭圆的动画。

python pyqt pyqt5
1个回答
1
投票

对于上位者提供的代码,很难知道错误在哪里(除了对象没有显示之外,还有很多元素没有声明),所以导致错误的原因可能有很多,所以我将避免这个问题,我只显示一个功能代码,而不是项目在QObject里面,它的信息被更新,我将使QObject暴露属性,并通过信号更新项目。

from PyQt5 import QtCore, QtGui, QtWidgets


class ManagerRectAnimation(QtCore.QObject):
    rectChanged = QtCore.pyqtSignal(QtCore.QRectF)

    def __init__(self, parent=None):
        super(ManagerRectAnimation, self).__init__(parent)
        self._rect = QtCore.QRectF()

        self._animation = QtCore.QPropertyAnimation(
            self, targetObject=self, propertyName=b"rect", duration=1000
        )

    @property
    def animation(self):
        return self._animation

    def rect(self):
        return self._rect

    def setRect(self, r):
        self._rect = r
        self.rectChanged.emit(r)

    rect = QtCore.pyqtProperty(
        QtCore.QRectF, fget=rect, fset=setRect, notify=rectChanged
    )


def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)

    scene = QtWidgets.QGraphicsScene()
    view = QtWidgets.QGraphicsView(scene)

    item = QtWidgets.QGraphicsEllipseItem()
    scene.addItem(item)

    manager_animation = ManagerRectAnimation(view)
    manager_animation.rectChanged.connect(item.setRect)
    manager_animation.animation.setStartValue(QtCore.QRectF(0, 0, 1, 1))
    manager_animation.animation.setEndValue(QtCore.QRectF(0, 0, 500, 500))
    manager_animation.animation.start()

    view.resize(640, 480)
    view.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.