pyqt5 QThread关闭子线程,停止正在执行的函数例子
时间: 2024-05-14 08:13:43 浏览: 96
很好,这是一个技术问题。以下是一个例子,可以用于关闭子线程并停止正在执行的函数:
```
import sys
import time
from PyQt5.QtCore import QThread, pyqtSignal, QObject
class Worker(QObject):
finished = pyqtSignal()
progress = pyqtSignal(int)
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
def run(self):
count = 0
while True:
time.sleep(1)
count += 1
self.progress.emit(count)
if count == 10:
break
self.finished.emit()
class ExampleThread(QThread):
def __init__(self, parent=None):
super(ExampleThread, self).__init__(parent)
self.worker = Worker()
def run(self):
self.worker.run()
def stop(self):
self.worker.terminate()
class Example():
def __init__(self):
self.thread = ExampleThread()
self.thread.finished.connect(self.on_finished)
self.thread.progress.connect(self.on_progress)
self.thread.start()
def on_finished(self):
print('Thread finished')
def on_progress(self, count):
print('Count:', count)
def stop_thread(self):
self.thread.stop()
if __name__ == '__main__':
app = QApplication(sys.argv)
example = Example()
time.sleep(3)
example.stop_thread()
sys.exit(app.exec_())
```
希望这个例子能够帮到你。
阅读全文