QPropertyAnimation doesn't work with a child w

2019-05-11 13:31发布

问题:

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_())

回答1:

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