我有这部分代码,有时可以工作,有时会发出警告:
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,并且您将引用存储在同一变量中,那么您可能需要将对象存储在列表中。但是,当给定线程完成时,您将需要从列表中清除对象(以便对它们进行垃圾回收),以免对应用程序造成内存泄漏。

关于python - QThread:当线程仍在Python中运行时被破坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34851261/

10-13 04:56