QPropertyAnimation与子部件不起作用

4 投票
1 回答
2666 浏览
提问于 2025-04-16 22:57

下面的代码没有像预期那样让按钮动起来。不过,如果这个按钮是单独使用的,它就能正常工作;但当它作为一个子部件时,就不行了。我这里出错了什么呢?

我是在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 个回答

6

我刚在Ubuntu 10.04上用PySide试了一下。建议你保持对动画对象的引用,这样可以解决这里的问题:

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

撰写回答