简体   繁体   中英

QThread: Destroyed while thread is still running

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

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__ . 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()

I know it's quite necroposting but this may be useful. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM