以下是一个简单的示例程序,其中包含了一个进度条和一个按钮,通过点击按钮来启动多进程任务,并在主进程中更新进度条:
import multiprocessing
import time
from PyQt5.QtCore import Qt, QTimer, pyqtSlot
from PyQt5.QtGui import QStandardItem, QStandardItemModel
from PyQt5.QtWidgets import QApplication, QMainWindow, QProgressBar, QPushButton, QTreeView, QVBoxLayout, QWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Multi-process Progress Bar")
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.layout = QVBoxLayout(self.central_widget)
self.progress_bar = QProgressBar()
self.layout.addWidget(self.progress_bar)
self.start_button = QPushButton("Start")
self.layout.addWidget(self.start_button)
self.tree_view = QTreeView()
self.layout.addWidget(self.tree_view)
self.model = QStandardItemModel()
self.model.setHorizontalHeaderLabels(['Task', 'Status', 'Progress'])
self.tree_view.setModel(self.model)
self.start_button.clicked.connect(self.start_task)
@pyqtSlot()
def start_task(self):
self.start_button.setEnabled(False)
self.progress_bar.setValue(0)
self.model.clear()
for i in range(4):
item = QStandardItem(f"Task {i}")
self.model.appendRow([item, QStandardItem("Pending"), QStandardItem("0%")])
self.tasks = []
for i in range(4):
task = multiprocessing.Process(target=self.do_task, args=(i,))
self.tasks.append(task)
task.start()
self.timer = QTimer()
self.timer.timeout.connect(self.update_progress)
self.timer.start(100)
def do_task(self, task_id):
for i in range(101):
time.sleep(0.05)
self.tasks[task_id].conn.send(i)
self.tasks[task_id].conn.close()
@pyqtSlot()
def update_progress(self):
for row in range(self.model.rowCount()):
task = self.model.item(row, 0)
status = self.model.item(row, 1)
progress = self.model.item(row, 2)
if status.text() == "Pending":
task_id = row
task_status = self.tasks[task_id].is_alive()
if task_status:
status.setText("Running")
progress_value = self.tasks[task_id].conn.recv()
progress.setText(f"{progress_value}%")
self.progress_bar.setValue(progress_value)
else:
status.setText("Done")
progress.setText("100%")
if not any(task.is_alive() for task in self.tasks):
self.start_button.setEnabled(True)
self.timer.stop()
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
在这个程序中,我们使用 multiprocessing
模块来创建了四个子进程,并且在每个子进