[英]QThread: Destroyed while thread is still running in Python
我有这部分代码,有时可以工作,有时会发出警告:
QThread: Destroyed while thread is still running
这部分在UiMainWindow类中
obj_thread = QtCore.QThread()
def ok():
self.module_src_tree.setStyleSheet('background-color: #81F781')
obj_thread.quit()
def err():
self.module_src_tree.setStyleSheet('background-color: #F78181')
obj_thread.quit()
tmp = self.Temp(self, module_revision)
tmp.moveToThread(obj_thread)
tmp.finished.connect(ok)
tmp.error.connect(err)
obj_thread.started.connect(tmp.run)
obj_thread.start()
这是UiMainWindow类中的类
class Temp(QtCore.QObject):
finished = QtCore.pyqtSignal()
error = QtCore.pyqtSignal()
def __init__(self, gui, module_revision):
QtCore.QObject.__init__(self)
self.gui = gui
self.module_revision = module_revision
def run(self):
try:
self.gui.dp.pack_module_source(self.gui.module_src_show_list, self.gui.module_src_pack_list,
path=str(self.gui.path_box.text()), revision=self.module_revision)
self.finished.emit()
except Exception as e:
self.error.emit()
raise e
我想用此代码做什么-我想压缩一些文件而不冻结主应用程序。 所以我开始在后台工作的新线程。 但是我需要的功能是,在完成压缩后,小部件可以将其颜色更改为绿色或红色(如果出了问题)。
也许我做错了什么? 也许那不是办法吗?
我最常遇到的问题是要改变颜色。
最好的祝福,
马雷克
@three_pineapples,似乎好像有时根本没有开始。 但是现在没有错误/警告。
我已经对此进行了修改:
class UiMainWindow(object):
# thread pool
thread_pool = [None, None, None, None]
这是在类构造函数之前。 Temp类保持与上面相同,并且Thread调用代码的一部分现在看起来像这样:
self.thread_pool[3] = None
self.thread_pool[3] = QtCore.QThread()
def ok():
self.module_src_tree.setStyleSheet('background-color: #81F781')
self.thread_pool[3].quit()
def err():
self.module_src_tree.setStyleSheet('background-color: #F78181')
self.thread_pool[3].quit()
tmp = self.Temp(self, module_revision)
tmp.moveToThread(self.thread_pool[3])
tmp.finished.connect(ok)
tmp.error.connect(err)
self.thread_pool[3].started.connect(tmp.run)
self.thread_pool[3].start()
当线程被Python垃圾回收时,会发生此问题。
您需要保存对您的QThread
的引用,以便不会对其进行垃圾回收。 只是做self.obj_thread = QtCore.QThread()
如果有可能同时存在多个QThread
,并且您将引用存储在同一变量中,那么您可能需要将对象存储在列表中。 但是,当给定线程完成时,您将需要从列表中清除对象(以便对它们进行垃圾收集),以免对应用程序造成内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.