使用python、pyqt6写一个界面,有两个按键和两个进度条,两个按键里面有耗时操作,要求每个按键都能独自更新进度条,不卡界面
时间: 2024-01-17 21:06:00 浏览: 30
好的,以下是一个使用Python和PyQt6实现的示例程序,其中有两个按键和两个进度条,每个按键都会执行一个耗时操作,并且每个按键对应的进度条都会独立更新,不会卡界面:
```python
import sys
import time
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QMutex
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QGridLayout, QWidget, QProgressBar
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.button1 = QPushButton('Button 1', self)
self.button1.clicked.connect(self.on_button1_clicked)
self.progress1 = QProgressBar(self)
self.progress1.setAlignment(Qt.AlignCenter)
self.button2 = QPushButton('Button 2', self)
self.button2.clicked.connect(self.on_button2_clicked)
self.progress2 = QProgressBar(self)
self.progress2.setAlignment(Qt.AlignCenter)
layout = QGridLayout()
layout.addWidget(self.button1, 0, 0)
layout.addWidget(self.button2, 0, 1)
layout.addWidget(self.progress1, 1, 0)
layout.addWidget(self.progress2, 1, 1)
self.setLayout(layout)
self.mutex1 = QMutex()
self.mutex2 = QMutex()
def on_button1_clicked(self):
self.thread1 = MyThread('Thread 1', self.mutex1)
self.thread1.progress.connect(self.progress1.setValue)
self.thread1.start()
def on_button2_clicked(self):
self.thread2 = MyThread('Thread 2', self.mutex2)
self.thread2.progress.connect(self.progress2.setValue)
self.thread2.start()
class MyThread(QThread):
progress = pyqtSignal(int)
def __init__(self, name, mutex):
super().__init__()
self.name = name
self.mutex = mutex
def run(self):
start_time = time.monotonic()
while time.monotonic() - start_time < 10:
# 模拟耗时操作
time.sleep(0.1)
# 计算进度值并发射信号
elapsed = time.monotonic() - start_time
progress = int(elapsed / 10 * 100)
self.mutex.lock()
self.progress.emit(progress)
self.mutex.unlock()
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Non-blocking UI Demo')
self.setCentralWidget(MyWidget())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec())
```
在该程序中,我们通过使用 QThread 和 pyqtSignal 来实现耗时操作的异步执行,并使用 QMutex 来保证每个线程对应的进度条的独立更新,以避免多个线程同时修改同一个进度条导致的线程安全问题。每个线程会定期计算进度值并发射信号,在信号槽机制的作用下,进度条会自动更新。而其他的事件则通过 QApplication.processEvents() 来处理,以保证UI界面的响应性。
需要注意的是,如果使用 QThread 来实现多线程编程,需要确保线程在执行完毕后能够正常退出,否则可能会导致内存泄漏等问题。在本程序中,我们使用了 QMutex 来保证线程的正常退出。