gpt4 book ai didi

python - QThread:线程仍在运行时被销毁

转载 作者:太空狗 更新时间:2023-10-29 17:02:34 25 4
gpt4 key购买 nike

我在 python 中遇到 QThreads 问题。我想更改标签的背景颜色。但是我的应用程序在启动时崩溃了。“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_())

最佳答案

在线程创建后您没有存储对线程的引用,这意味着它会在程序离开 MainWindows __init__ 后的某个时间被垃圾收集(即销毁) 。您至少需要在线程运行时存储它,例如使用 self.statusTh:

self.statusTh = statusThread(self)
self.connect(self.statusTh, SIGNAL('setStatus'), self.st, Qt.QueuedConnection)
self.statusTh.start()

关于python - QThread:线程仍在运行时被销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15702782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com