pyqt5 QThread: Destroyed while thread is still running这个报警怎么解决?代码演示
时间: 2023-07-26 13:48:05 浏览: 68
以下是一个简单的示例代码,演示如何在PyQt5中使用QThread类,并在QThread对象销毁之前停止线程以避免QThread: Destroyed while thread is still running报警。
```python
import sys
import time
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton
class MyThread(QThread):
finished = pyqtSignal()
message = pyqtSignal(str)
def __init__(self):
super().__init__()
self.m_stop = False
def stop(self):
self.m_stop = True
def run(self):
while not self.m_stop:
self.message.emit("Thread is running...")
time.sleep(1)
self.message.emit("Thread is stopped!")
self.finished.emit()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.label = QLabel(self)
self.label.setGeometry(50, 50, 200, 30)
self.button = QPushButton('Stop', self)
self.button.setGeometry(50, 100, 100, 30)
self.button.clicked.connect(self.stopThread)
self.thread = MyThread()
self.thread.message.connect(self.updateLabel)
self.thread.finished.connect(self.threadFinished)
self.thread.start()
@pyqtSlot(str)
def updateLabel(self, text):
self.label.setText(text)
def stopThread(self):
self.thread.stop()
@pyqtSlot()
def threadFinished(self):
self.thread.quit()
self.thread.wait()
print("Thread is finished!")
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在上面的示例代码中,我们定义了一个MyThread类继承自QThread,在run()函数中实现了线程的执行逻辑,并在stop()函数中发送停止信号给线程。我们还定义了一个message信号,用于在UI线程中更新标签的文本。
在主窗口类中,我们创建了一个标签和一个按钮,并将按钮的clicked信号连接到stopThread()函数。在initUI()函数中,我们创建了一个MyThread对象并启动它,并将message信号连接到updateLabel()函数,将finished信号连接到threadFinished()函数。
在stopThread()函数中,我们发送停止信号给线程。在threadFinished()函数中,我们先使用quit()函数停止线程的事件循环,然后使用wait()函数等待线程完成,并在完成后关闭主窗口。
这样,我们就能够在QThread对象销毁之前正确地停止线程,避免了QThread: Destroyed while thread is still running报警。