pyqt5 当主窗口进行一个任务时,显示一个进度框,可以随时通过进度框取消该任务
时间: 2023-06-14 10:04:13 浏览: 117
python3.x+pyqt5实现主窗口状态栏里(嵌入)显示进度条功能
PyQt5中可以使用QProgressDialog来显示进度对话框,并通过QProgressDialog.canceled()信号来检测用户是否点击了取消按钮。下面是一个简单的示例代码:
```python
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QProgressBar, QPushButton, QVBoxLayout, QProgressDialog
class Worker(QThread):
progressChanged = pyqtSignal(int)
def __init__(self):
super().__init__()
self.isCanceled = False
def run(self):
for i in range(100):
if self.isCanceled:
return
self.progressChanged.emit(i)
self.msleep(100)
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.progress = QProgressBar(self)
self.progress.setMinimum(0)
self.progress.setMaximum(99)
self.startButton = QPushButton("Start", self)
self.startButton.clicked.connect(self.startTask)
layout = QVBoxLayout()
layout.addWidget(self.progress)
layout.addWidget(self.startButton)
self.setLayout(layout)
self.setGeometry(100, 100, 300, 100)
self.setWindowTitle("Progress Dialog Example")
self.show()
def startTask(self):
dialog = QProgressDialog("Task in progress.", "Cancel", 0, 100, self)
dialog.setWindowModality(Qt.ApplicationModal)
dialog.canceled.connect(self.cancelTask)
dialog.show()
self.worker = Worker()
self.worker.progressChanged.connect(self.updateProgress)
self.worker.start()
def updateProgress(self, value):
self.progress.setValue(value)
def cancelTask(self):
self.worker.isCanceled = True
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
app.exec_()
```
在这个示例代码中,我们定义了一个Worker类来执行任务,并通过progressChanged信号来更新进度。在主窗口中,我们创建了一个QProgressDialog来显示进度对话框,并通过canceled信号来检测用户是否点击了取消按钮。当用户点击取消按钮时,我们设置Worker的isCanceled属性为True,以停止任务的执行。
阅读全文