前言:
在 PyQt5 中,QProgressBar
用于显示进度(如文件下载、任务执行进度等)。下面是一个完整的示例,展示如何在窗口中添加进度条并更新它:
基础示例:按钮控制进度条更新
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QProgressBar
from PyQt5.QtCore import QTimer
class ProgressBarDemo(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt5 ProgressBar Example")
self.setGeometry(100, 100, 300, 100)
self.layout = QVBoxLayout()
self.progress = QProgressBar(self)
self.progress.setValue(0)
self.progress.setMaximum(100)
self.button = QPushButton("Start Progress", self)
self.button.clicked.connect(self.start_progress)
self.layout.addWidget(self.progress)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
self.timer = QTimer()
self.timer.timeout.connect(self.update_progress)
self.progress_value = 0
def start_progress(self):
self.progress_value = 0
self.progress.setValue(self.progress_value)
self.timer.start(50) # update every 50 ms
def update_progress(self):
if self.progress_value >= 100:
self.timer.stop()
else:
self.progress_value += 1
self.progress.setValue(self.progress_value)
if __name__ == "__main__":
app = QApplication(sys.argv)
demo = ProgressBarDemo()
demo.show()
sys.exit(app.exec_())