【问题标题】:Animating a window on startup在启动时为窗口设置动画
【发布时间】:2013-12-06 18:19:58
【问题描述】:

我正在尝试在启动时为窗口设置动画,但它似乎不起作用,我已经编写了下面的代码。

from PyQt4 import QtCore,QtGui

import sys

class AnimatedWindow(QtGui.QMainWindow):
    """docstring for AnimatedWindow"""
    def __init__(self):
        super(AnimatedWindow, self).__init__()
        animation = QtCore.QPropertyAnimation(self, "geometry")
        animation.setDuration(10000);
        animation.setStartValue(QtCore.QRect(0, 0, 100, 30));
        animation.setEndValue(QtCore.QRect(250, 250, 100, 30));
        animation.start();


if __name__ == "__main__":
    application = QtGui.QApplication(sys.argv)
    main = AnimatedWindow()
    main.show()
    sys.exit(application.exec_())

【问题讨论】:

  • QPropertyAnimation 类在Qt 4.6 及以上版本中支持,您使用的是什么版本?

标签: qt pyqt pyqt4 pyside


【解决方案1】:

这段代码的问题是,当你创建一个QPropertyAnimation 的对象时,它会在animation.start() 语句后被python 垃圾收集器销毁,因为animation 变量是一个局部变量,因此动画不会发生。要克服这个问题,您需要将animation 作为成员变量 (self.animation)

这是更新后的代码,可以正常工作:

from PyQt4 import QtCore,QtGui

import sys

class AnimatedWindow(QtGui.QMainWindow):
    """docstring for AnimatedWindow"""
    def __init__(self):
        super(AnimatedWindow, self).__init__()
        self.animation = QtCore.QPropertyAnimation(self, "geometry")
        self.animation.setDuration(1000);
        self.animation.setStartValue(QtCore.QRect(50, 50, 100, 30));
        self.animation.setEndValue(QtCore.QRect(250, 250, 500, 530));
        self.animation.start();

if __name__ == "__main__":
    application = QtGui.QApplication(sys.argv)
    main = AnimatedWindow()
    main.show()
    sys.exit(application.exec_())

【讨论】:

  • 我正在通过给出问题的实际原因来更新这个答案
猜你喜欢
  • 2020-08-31
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多