[pyqt5] 多线程遇到QThread: Destroyed while thread is still running解决方法

[pyqt5] 多线程遇到QThread: Destroyed while thread is still running解决方法

在这里插入图片描述

当前我的程序是这样的,但是运行程序之后会报QThread: Destroyed while thread is still running的错

原因是在这个窗口MainWinodw类下,download_thread只是一个局部变量,按钮点击运行完这两行代码后就退出这个函数了,它的生命周期也就结束了,但是这个线程里的程序还在运行 所以才会报错,只要将他们改成类下的变量或者全局变量才不会报错。如下所示

self.download_thread = Music_Download_Thread(self.music_download,self.all_header_checkbox)
self.download_thread.start()
以下是一个简单的示例代码,演示如何在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报警。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锡城筱凯

你的鼓励是我创造的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值