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

PyQt5加载Spinner控件无限循环动画实现及相关问题咨询

PyQt5 加载Spinner控件无限循环动画问题解决

问题解答

1. 设置动画循环次数

你之前用self._animation.loopCount(50)是错误的——loopCount()是用于获取当前循环次数的方法,设置循环次数需要调用setLoopCount()。如果要实现无限循环,直接传入QtCore.QAbstractAnimation.Infinite即可,Qt动画框架会自动处理循环逻辑,无需手动在valueChanged信号中判断重启。

2. DeletionPolicy实现正确性

你在start()中传入KeepWhenStopped是正确的。这个参数指定动画停止后不自动删除动画对象,它也是start()方法的默认值,所以即使省略该参数也不会有问题,但显式声明能让代码意图更清晰。

修改后的完整代码

import os
from PyQt5 import QtCore, QtGui, QtWidgets

class Spinner(QtWidgets.QLabel):
    def __init__(self, *args, **kwargs):
        super(Spinner, self).__init__(*args, **kwargs)
        self._pixmap = QtGui.QPixmap()
        self._animation = QtCore.QVariantAnimation(
            self,
            startValue=0.0,
            endValue=360.0,
            duration=3000,
            valueChanged=self.on_valueChanged
        )
        # 设置无限循环
        self._animation.setLoopCount(QtCore.QAbstractAnimation.Infinite)
        # 启动动画,KeepWhenStopped为默认值,可省略
        if self._animation.state() != QtCore.QAbstractAnimation.Running:
            self._animation.start(QtCore.QAbstractAnimation.KeepWhenStopped)

    def set_pixmap(self, pixmap):
        self._pixmap = pixmap
        self.setPixmap(self._pixmap)

    @QtCore.pyqtSlot(QtCore.QVariant)
    def on_valueChanged(self, value):
        t = QtGui.QTransform()
        t.rotate(value)
        self.setPixmap(self._pixmap.transformed(t))


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        label = Spinner()
        label.setAlignment(QtCore.Qt.AlignCenter)
        label.set_pixmap(QtGui.QPixmap("load.png"))
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(label)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

额外说明

  • 动画会自动无限循环,直到调用self._animation.stop()手动停止
  • 移除了原代码中valueChanged里判断value == 360.0的重启逻辑,因为Qt会根据设置的循环次数自动处理动画重置
  • 若后续需要改为有限次数循环,只需将Infinite替换为具体数字(比如50)即可

内容的提问来源于stack exchange,提问作者Derek Clark

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:10:14