首页 > 解决方案 > 可以为 QProgressBar 设置格式以在 pyqt5 中显示带前导零的值吗?

问题描述

考虑这个例子,修改自https://www.geeksforgeeks.org/pyqt5-qprogressbar-how-to-create-progress-bar/

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
import time
class Example(QWidget):
  def __init__(self):
    super().__init__()
    # calling initUI method
    self.initUI()
  # method for creating widgets
  def initUI(self):
    # creating progress bar
    self.pbar = QProgressBar(self)
    # setting its geometry
    self.pbar.setGeometry(30, 40, 200, 25)
    # creating push button
    self.btn = QPushButton('Start', self)
    # changing its position
    self.btn.move(40, 80)
    # adding action to push button
    self.btn.clicked.connect(self.doAction)
    # setting window geometry
    self.setGeometry(300, 300, 280, 170)
    # setting window action
    self.setWindowTitle("Python")
    # set format of progress bar:
    #self.pbar.setFormat("Hello world %v of %m") # works fine
    print("Just testing leading zeroes: %04d"%12) # ok, prints 0012
    self.pbar.setFormat("Hello world %04v of %04m") # leading zeroes? Nope
    # showing all the widgets
    self.show()
  # when button is pressed this method is being called
  def doAction(self):
    self.pbar.setMaximum(100)
    # setting for loop to set value of progress bar
    for i in range(101):
      # slowing down the loop
      time.sleep(0.05)
      # setting value to progress bar
      self.pbar.setValue(i)
# main method
if __name__ == '__main__':

  # create pyqt5 app
  App = QApplication(sys.argv)
  # create the instance of our Window
  window = Example()
  # start the app
  sys.exit(App.exec())

用于self.pbar.setFormat("Hello world %v of %m")打印进度条的当前值和最大值可以正常工作。

现在,我想做同样的事情,但当前值和最大值被格式化为最多 4 个前导零。

所以,考虑到例如print("%04d"%12)打印0012- 我试过self.pbar.setFormat("Hello world %04v of %04m")- 但它根本不格式化数字:

进度条

那么,是否可以以某种方式设置进度条的格式,以便将当前值和最大值格式化为带有前导零的整数?

标签: pythonpyqt5

解决方案


一个可能的解决方案是重写text()QProgressBar 的方法:

from PyQt5 import QtWidgets


class ProgressBar(QtWidgets.QProgressBar):
    def text(self):
        return self.format() % dict(m=self.value(), v=(self.maximum() - self.minimum()))


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = ProgressBar()
    w.setMaximum(100)
    w.setValue(5)
    w.setFormat("Hello world %(m)04d of %(v)04d")
    w.show()
    sys.exit(app.exec())

推荐阅读