PyQt5 如何在进度条中显示小数点值

  • Post category:Python

使用PyQt5在进度条中显示小数点值的方法,可以结合QProgressBar和QTimer类实现。具体操作步骤如下:

1.导入PyQt5库:

from PyQt5 import QtWidgets, QtCore

2.创建一个窗口类,并在其中添加一个进度条,设置进度条初始值为0:

class MyWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.progressBar = QtWidgets.QProgressBar(self)
        self.progressBar.setGeometry(30, 20, 200, 25)
        self.progressBar.setValue(0)

3.设置一个定时器,在定时器中更新进度条的值,并用QFormatSting方法设置进度条数值的格式:

def start_transition(self, progressbar):
    self.timer = QtCore.QTimer(self)
    self.timer.timeout.connect(lambda: self.update_progress(progressbar))
    self.timer.start(100)

def update_progress(self, progressbar):
    value = progressbar.value()
    if value < 100:
        progressbar.setValue(value + 1)
        progressbar.setFormat("{:.1f}%".format(value + 1))
    else:
        self.timer.stop()

4.最后,在窗口中调用start_transition方法开始进度条的动态显示:

def main():
    app = QtWidgets.QApplication(sys.argv)
    win = MyWindow()
    win.show()
    win.start_transition(win.progressBar)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

完整代码如下:

import sys
from PyQt5 import QtWidgets, QtCore


class MyWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.progressBar = QtWidgets.QProgressBar(self)
        self.progressBar.setGeometry(30, 20, 200, 25)
        self.progressBar.setValue(0)

    def start_transition(self, progressbar):
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(lambda: self.update_progress(progressbar))
        self.timer.start(100)

    def update_progress(self, progressbar):
        value = progressbar.value()
        if value < 100:
            progressbar.setValue(value + 1)
            progressbar.setFormat("{:.1f}%".format(value + 1))
        else:
            self.timer.stop()


def main():
    app = QtWidgets.QApplication(sys.argv)
    win = MyWindow()
    win.show()
    win.start_transition(win.progressBar)
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

示例一:如果想设置进度条每次增加的步长为0.5,可以在update_progress中修改如下:

def update_progress(self, progressbar):
    value = progressbar.value()
    if value < 100:
        progressbar.setValue(value + 0.5)
        progressbar.setFormat("{:.1f}%".format(value + 0.5))
    else:
        self.timer.stop()

示例二:如果想设置进度条的总共步数为200步,可以在update_progress中修改如下:

def start_transition(self, progressbar):
    self.timer = QtCore.QTimer(self)
    self.timer.timeout.connect(lambda: self.update_progress(progressbar))
    self.timer.start(100)

def update_progress(self, progressbar):
    value = progressbar.value()
    if value < 200:
        progressbar.setValue(value + 1)
        progressbar.setFormat("{:.1f}%".format((value + 1) / 2))
    else:
        self.timer.stop()

修改后,进度条的步数为200,进度条的显示值变为小数(例如:1,1.5,2,2.5,……,99.5,100)。