[英]QThread: Destroyed while thread is still running
I'm having problem with QThreads in python.我在 python 中遇到 QThreads 问题。 I want to change background color of label.我想更改 label 的背景颜色。 But My application crash while starting.但是我的应用程序在启动时崩溃了。 "QThread: Destroyed while thread is still running" “QThread:在线程仍在运行时被销毁”
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
statusTh = statusThread(self)
self.connect(statusTh, SIGNAL('setStatus'), self.st, Qt.QueuedConnection)
statusTh.start()
def st(self):
if self.status == 'ON':
self.ui.label.setStyleSheet('background-color:green')
else:
self.ui.label.setStyleSheet('background-color:red')
class statusThread(QThread):
def __init__(self, mw):
super(statusThread, self).__init__()
def run(self):
while True:
time.sleep(1)
self.emit(SIGNAL('setStatus'))
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
You're not storing a reference to the thread after it's been created, which means that it will be garbage collected (ie. destroyed) some time after the program leaves MainWindow
s __init__
. 你没有在创建线程后存储对线程的引用,这意味着在程序离开MainWindow
的__init__
之后的某个时间它将被垃圾收集(即销毁)。 You need to store it at least as long as the thread is running, for example use self.statusTh
: 只要线程正在运行,您至少需要存储它,例如使用self.statusTh
:
self.statusTh = statusThread(self)
self.connect(self.statusTh, SIGNAL('setStatus'), self.st, Qt.QueuedConnection)
self.statusTh.start()
I know it's quite necroposting but this may be useful.我知道这是相当的 necroposting 但这可能很有用。 In the main section of your script, a first level customized widget need to be stored in variable, not only created.在脚本的主要部分中,需要将第一级自定义小部件存储在变量中,而不仅仅是创建。 For example I have a custom widget class called MainWindow that create a QThread.例如,我有一个名为 MainWindow 的自定义小部件 class,它创建了一个 QThread。 My main is like that:我的主要是这样的:
from myPackage import MainWindow
if __name__ == "__main__":
app = QApplication([])
widget=MainWindow()
sys.exit(app.exec())
if I avoid the widged = definition and only call for MainWindow(), my script will crash with QThread: Destroyed while thread is still running如果我避免使用widged =定义并且只调用 MainWindow(),我的脚本将与QThread 崩溃:线程仍在运行时已销毁
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.