[英]Possible to setFormat for QProgressBar to show values with leading zeroes in 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")
- 但它根本不格式化數字:
那么,是否可以以某種方式設置進度條的格式,以便將當前值和最大值格式化為帶有前導零的整數?
一個可能的解決方案是覆蓋 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.