pyqt5 实现在线程QtCore.QThread内部终止线程,示例
时间: 2024-05-05 08:17:43 浏览: 141
代码如下:
```python
import sys
import time
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class Worker(QThread):
finished = pyqtSignal()
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
self.is_running = True
def stop(self):
self.is_running = False
def run(self):
while self.is_running:
time.sleep(1)
print('working...')
self.finished.emit()
class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle('Thread Example')
self.button_start = QPushButton('Start', self)
self.button_stop = QPushButton('Stop', self)
self.button_stop.setEnabled(False)
layout = QVBoxLayout()
layout.addWidget(self.button_start)
layout.addWidget(self.button_stop)
self.setLayout(layout)
self.thread = Worker()
self.button_start.clicked.connect(self.start_thread)
self.button_stop.clicked.connect(self.stop_thread)
def start_thread(self):
self.thread.is_running = True
self.thread.start()
self.button_start.setEnabled(False)
self.button_stop.setEnabled(True)
def stop_thread(self):
self.thread.stop()
self.thread.finished.connect(self.thread_finished)
def thread_finished(self):
self.button_start.setEnabled(True)
self.button_stop.setEnabled(False)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
希望这个示例代码对你有帮助!现在,你可以继续问我其它问题了。
阅读全文