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

PyQt5修改背景样式表实现环形进度条无实时渲染效果如何解决?

PyQt5环形进度条样式不实时更新的解决方法

问题原因

  • 核心错误是样式表模板被首次替换后永久覆盖,后续无可用占位符完成替换:你在初始化时将带{STOP_1}、{STOP_2}占位符的字符串赋值给self.styleSheet,但第一次调用进度更新方法时,直接对self.styleSheet做了替换并重新赋值,此时该属性内已经没有占位符,后续所有替换操作都无法匹配生效,相当于样式表从第一次赋值后就再也没有被实际修改,所以只有定时器结束后才会显示最终状态。
  • 次要优化点:锥形渐变的stop值必须在0~1区间内,当进度为100%时value-0.001会出现负数,会导致渐变渲染异常。

修复方案

修改逻辑为保留原始样式模板,每次更新都基于模板生成新的样式字符串,同时增加重绘调用确保渲染及时,修复后的代码如下:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from gui import Ui_MainWindow
from PyQt5.QtCore import QTimer


class Nem_Gui(QMainWindow):
    
    def __init__(self):
        super(Nem_Gui,self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.count=0
        # 把模板单独存为固定属性,不要修改它
        self.progress_style_template = "QFrame#circular_progress{\n border-radius:150;\n background-color: qconicalgradient(cx:0.5, cy:0.5, angle:90, stop:{STOP_1} rgba(0, 0, 0, 255), stop:{STOP_2} rgba(85, 85, 255, 255));\n}"          

        # 设置定时器
        self.timerbar=QTimer(self)
        self.timerbar.start(35)
        self.timerbar.timeout.connect(self.update_progress)

    def update_progress(self):
        if self.count>=100:
            self.timerbar.stop()
        else:
            self.count+=1
            self.set_progress(self.count)


    def set_progress(self,value):
        progress = (100-value)/100.0
        # 每次都用原始模板生成新样式,避免占位符丢失,同时限制stop值不小于0
        stop1 = max(progress - 0.001, 0)
        stop2 = progress
        current_style = self.progress_style_template.replace("{STOP_1}", str(stop1)).replace("{STOP_2}", str(stop2))
        self.ui.circular_progress.setStyleSheet(current_style)
        # 强制控件重绘,确保样式实时生效
        self.ui.circular_progress.update()
        

 
        
def run():
    app=QApplication(sys.argv)
    win=Nem_Gui()
    win.show()
    sys.exit(app.exec_())
run()

额外优化建议

  • 如果觉得35ms的刷新频率不够流畅,可以把定时器间隔调整到16ms(对应60fps的刷新率),动画会更丝滑。
  • 锥形渐变的角度可以根据需求调整,实现不同的进度起始方向。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:15:07