pyqt5 progressbar显示小数
时间: 2023-10-25 12:19:36 浏览: 134
progressbar
PyQt5 的 QProgressBar 组件只能显示整数,如果需要显示小数,则需要自定义一个组件。以下是一个简单的例子:
```python
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPainter, QColor, QBrush
from PyQt5.QtWidgets import QWidget, QApplication, QProgressBar
class DecimalProgressBar(QProgressBar):
def __init__(self, parent=None):
super(DecimalProgressBar, self).__init__(parent)
def paintEvent(self, event):
# 绘制进度条
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(Qt.NoPen)
painter.setBrush(QColor(0, 0, 255, 50))
rect = QRectF(0, 0, (self.width() * self.value() / self.maximum()), self.height())
painter.drawRect(rect)
# 绘制进度文本
text = "{:.2f}%".format(self.value() / self.maximum() * 100)
painter.setPen(QColor(0, 0, 0))
painter.drawText(self.rect(), Qt.AlignCenter, text)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = QWidget()
progress = DecimalProgressBar(window)
progress.setGeometry(50, 50, 200, 30)
progress.setMaximum(100)
progress.setValue(50.5)
window.show()
sys.exit(app.exec_())
```
在上面的例子中,我们继承了 QProgressBar 组件,重写了 paintEvent 方法,在其中绘制了进度条和进度文本。其中,进度条的长度是通过计算当前值和最大值的比例得到的,进度文本使用了 Python 的格式化字符串来显示小数。
阅读全文