4

The below code doesn't animate the button as expected. But it works if the button is stand alone and stops working when it is a child widget. What am I doing wrong here?

I'm trying this on Ubuntu.

class TestWindow(QtGui.QWidget):

    def __init__(self):
        QtGui.QWidget.__init__(self)

        self.button = QtGui.QPushButton("Ok")
        self.button.setParent(self)
        self.button.setGeometry(QtCore.QRect(0,0,50,50))
        self.button.clicked.connect(self.anim)

    def anim(self):

        animation = QtCore.QPropertyAnimation(self.button, "geometry")
        animation.setDuration(10000)
        animation.setStartValue(QtCore.QRect(0,0,0,0))
        animation.setEndValue(QtCore.QRect(0,0,200,200))
        animation.start()

if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)

        r = TestWindow()
        r.show()

        sys.exit(app.exec_())
Anoop
  • 1,307
  • 1
  • 14
  • 27

1 Answers1

6

I've just tried it on Ubuntu 10.04 with PySide. Try to keep a reference to your animation object, it solved the problem here:

def anim(self):

    animation = QtCore.QPropertyAnimation(self.button, "geometry")
    animation.setDuration(10000)
    animation.setStartValue(QtCore.QRect(0,0,0,0))
    animation.setEndValue(QtCore.QRect(0,0,200,200))
    animation.start()

    self.animation = animation
fviktor
  • 2,861
  • 20
  • 24
  • This was far from obvious and absent from the documentation - thanks! – Junuxx Oct 05 '13 at 11:38
  • I realize the age of my response, but this is an issue with Python's memory management system and C++/Qt rather than Qt's documentation. When the `animation` object goes out of scope from the `anim(self)` function (if it is not referenced into `self`) then Python will prematurely garbage collect `animation`. This will ofc cause the animation to fail; therefore, you must keep a reference of the animation. – Michael Choi Aug 07 '19 at 17:27