如何在PyQt5中同时运行位移和透明度两个QPropertyAnimation动画
问题原因
你的两个动画对象都赋值给了同一个实例属性self.animation,调用第二个动画函数时,第一个位移动画的对象会被覆盖,没有引用的动画对象会被Python垃圾回收,自然不会执行。
解决方案
方案1:分别用不同属性存储动画
直接修改两个动画函数的存储变量名,避免互相覆盖即可:
def title_intro(self): # 用单独的属性存储位移动画 self.geometry_animation = QtCore.QPropertyAnimation(self.ui.title_image, b"geometry") self.geometry_animation.setDuration(500) self.geometry_animation.setStartValue(QtCore.QRect(190, -60, 671, 261)) self.geometry_animation.setEndValue(QtCore.QRect(190, 0, 671, 261)) self.geometry_animation.start() def title_intro_opacity(self): self.opacity_effect = QtWidgets.QGraphicsOpacityEffect() self.ui.title_image.setGraphicsEffect(self.opacity_effect) # 用单独的属性存储透明度动画 self.opacity_animation = QtCore.QPropertyAnimation(self.opacity_effect, b"opacity") self.opacity_animation.setDuration(500) self.opacity_animation.setStartValue(0) self.opacity_animation.setEndValue(1) self.opacity_animation.start()
方案2:使用QParallelAnimationGroup并行管理动画(更推荐)
Qt原生提供的并行动画组可以统一管理多个同步执行的动画,无需维护多个独立的动画变量,逻辑更清晰,也方便后续扩展动画回调:
class MainWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.start_title_animation() self.show() def start_title_animation(self): # 1. 初始化位移动画 geometry_animation = QtCore.QPropertyAnimation(self.ui.title_image, b"geometry") geometry_animation.setDuration(500) geometry_animation.setStartValue(QtCore.QRect(190, -60, 671, 261)) geometry_animation.setEndValue(QtCore.QRect(190, 0, 671, 261)) # 2. 初始化透明度动画 self.opacity_effect = QtWidgets.QGraphicsOpacityEffect() self.ui.title_image.setGraphicsEffect(self.opacity_effect) opacity_animation = QtCore.QPropertyAnimation(self.opacity_effect, b"opacity") opacity_animation.setDuration(500) opacity_animation.setStartValue(0) opacity_animation.setEndValue(1) # 3. 加入并行动画组统一启动 self.animation_group = QtCore.QParallelAnimationGroup() self.animation_group.addAnimation(geometry_animation) self.animation_group.addAnimation(opacity_animation) self.animation_group.start()
内容的提问来源于stack exchange,提问作者Sam Leighton
相关产品推荐
相关产品推荐

