Pyqt中让progressbar实时显示Qprocess进度
时间: 2023-12-25 09:06:24 浏览: 187
可以使用`QProcess`的`readyReadStandardOutput()`或`readyReadStandardError()`信号来获取进程的输出,从而获取进度信息,并将其更新到`QProgressBar`上。
例如:
```python
import sys
from PyQt5.QtCore import Qt, QProcess
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QProgressBar, QPushButton, QTextEdit
class ProcessDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.process = QProcess(self)
self.process.setProcessChannelMode(QProcess.MergedChannels)
self.process.readyReadStandardOutput.connect(self.read_output)
self.process.finished.connect(self.finished)
self.progress_bar = QProgressBar(self)
self.progress_bar.setAlignment(Qt.AlignCenter)
self.progress_bar.setRange(0, 100)
self.log = QTextEdit(self)
self.log.setReadOnly(True)
self.button = QPushButton('Start', self)
self.button.clicked.connect(self.start_process)
layout = QVBoxLayout(self)
layout.addWidget(self.progress_bar)
layout.addWidget(self.log)
layout.addWidget(self.button)
def start_process(self):
self.button.setEnabled(False)
self.process.start('ping', ['-c', '10', 'www.baidu.com'])
def read_output(self):
output = self.process.readAll().data().decode()
self.log.append(output)
if 'time=' in output:
progress = int(output.split('time=')[1].split()[0])
self.progress_bar.setValue(progress)
def finished(self):
self.button.setEnabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = ProcessDialog()
dialog.show()
sys.exit(app.exec_())
```
上述代码中,使用`ping`命令模拟进程,并通过`readyReadStandardOutput()`信号获取进程的输出。在输出中找到进度信息,并将其更新到`QProgressBar`上。同时,将输出信息显示在`QTextEdit`上。
阅读全文