[英]Possible to setFormat for QProgressBar to show values with leading zeroes in pyqt5?
Consider this example, modified from https://www.geeksforgeeks.org/pyqt5-qprogressbar-how-to-create-progress-bar/ :考虑这个例子,修改自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())
Using self.pbar.setFormat("Hello world %v of %m")
to print out the current and max value of the progress bar works fine.使用
self.pbar.setFormat("Hello world %v of %m")
打印出进度条的当前和最大值工作正常。
Now, I would like to do the same, but with the current value and max being formatted with up to 4 leading zeroes.现在,我想做同样的事情,但当前值和最大值被格式化为最多 4 个前导零。
So, considering that eg print("%04d"%12)
prints 0012
- I tried self.pbar.setFormat("Hello world %04v of %04m")
- but it does not format numbers at all:因此,考虑到例如
print("%04d"%12)
打印0012
- 我尝试过self.pbar.setFormat("Hello world %04v of %04m")
- 但它根本不格式化数字:
So, is it possible to set the format of the progress bar somehow, so it formats the current and the max value as integers with leading zeroes?那么,是否可以以某种方式设置进度条的格式,以便将当前值和最大值格式化为带有前导零的整数?
A possible solution is to override the text()
method of QProgressBar:一个可能的解决方案是覆盖 QProgressBar 的
text()
方法:
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.