簡體   English   中英

QThread:當線程仍在Python中運行時被破壞

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM