PyQt中QMainWindow退出前执行的窗口透明度动画无法运行
问题解决:PyQt窗口关闭动画无法执行的问题
问题根源很直接:你在启动动画后立刻调用QApplication.exit(),这会立即终止整个应用程序——动画还没来得及渲染任何帧就被打断了,自然看不到效果。
正确的做法是等动画完全结束后再退出应用,利用PyQt的信号槽机制就能实现:
修改你的mousePressEvent方法,移除直接调用QApplication.exit()的代码,转而将动画的finished信号绑定到退出操作:
class MasterWindow(QMainWindow): close_if_clicked=True # [more code here] def mousePressEvent(self, a0: QtGui.QMouseEvent) -> None: if a0.button()==Qt.MouseButton.LeftButton and self.close_if_clicked: self.animation = QPropertyAnimation(self, b"windowOpacity") self.animation.setDuration(1000) self.animation.setStartValue(1.0) self.animation.setEndValue(0.0) self.animation.setEasingCurve(QEasingCurve.Type.InOutQuad) # 动画结束后再退出应用 self.animation.finished.connect(QApplication.exit) self.animation.start()
额外注意事项
- 必须用
self.animation保存动画对象,不能用局部变量,否则Python的垃圾回收会在函数结束后销毁动画,导致动画中途停止 - 如果你的需求只是关闭当前窗口而非退出整个应用,可以把
QApplication.exit()替换成self.close(),但此时需要重写closeEvent来处理动画逻辑(不过你的场景是退出应用,上面的代码已足够)
内容的提问来源于stack exchange,提问作者Chetan Sharma0402
相关产品推荐
相关产品推荐

