You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5 QStackedWidget切换时main_widget动画前闪现问题求助

QStackedWidget切换时main_widget闪现的解决办法

问题根源是:调用stacked_widget.setCurrentWidget(main_widget)时,QStackedWidget会立刻把main_widget显示在窗口里,这就导致动画还没开始,部件先闪了一下。

直接按下面的步骤改就行:

  1. 初始化时把main_widget藏到窗口外面
    创建完main_widget后,直接把它移到主窗口下方,这样切换的时候用户完全看不到:

    # 假设self是你的主窗口实例
    self.main_widget.move(0, self.height())
    
  2. 重写show_main_widget的动画逻辑
    先切换到main_widget(此时它在窗口外),再执行滑入动画,而不是依赖QStackedWidget的默认显示:

    def show_main_widget(self):
        self.stacked_widget.setCurrentWidget(self.main_widget)
        # 做从下方滑入的动画
        slide_in_anim = QPropertyAnimation(self.main_widget, b"pos")
        slide_in_anim.setDuration(500)
        # 起始位置是窗口下方,结束位置是窗口左上角
        slide_in_anim.setStartValue(QPoint(0, self.height()))
        slide_in_anim.setEndValue(QPoint(0, 0))
        slide_in_anim.start(QAbstractAnimation.DeleteWhenStopped)
    
  3. 调整welcome_widget的滑出动画触发时机
    确保welcome_widget滑出动画结束后再触发main_widget的滑入,比如在enter_the_app里把动画的finished信号连接到show_main_widget:

    def enter_the_app(self):
        slide_out_anim = QPropertyAnimation(self.welcome_widget, b"pos")
        slide_out_anim.setDuration(500)
        slide_out_anim.setStartValue(QPoint(0, 0))
        slide_out_anim.setEndValue(QPoint(0, -self.welcome_widget.height()))
        # 滑出完再启动主部件的滑入
        slide_out_anim.finished.connect(self.show_main_widget)
        slide_out_anim.start(QAbstractAnimation.DeleteWhenStopped)
    

这么改之后,main_widget就不会提前闪现了,两个动画衔接也会更流畅。

内容的提问来源于stack exchange,提问作者William Dartois

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 00:47:14