QThread:线程仍在运行时被销毁 [英] QThread: Destroyed while thread is still running

查看:70
本文介绍了QThread:线程仍在运行时被销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中遇到 QThreads 问题.我想更改标签的背景颜色.但是我的应用程序在启动时崩溃了.QThread:线程仍在运行时被销毁"

I'm having problem with QThreads in python. I want to change background color of label. But My application crash while starting. "QThread: Destroyed while thread is still running"

   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_())

推荐答案

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

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 MainWindows __init__. You need to store it at least as long as the thread is running, for example use self.statusTh:

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

这篇关于QThread:线程仍在运行时被销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆