PyQt QThread: destroyed while thread is still running

Despite saving the link to QThreadhow self.lightsThread, stopping QObject self.lightsWorkerand then starting self.lightsThreadagain caused an error

QThread: Destroyed while thread is still running

After stopping, self.lightsWorkeryou must also stop QThread self.lightsThread? If not, what is the problem?

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import time



class Screen(QMainWindow):
    def __init__(self):
        super(Screen, self).__init__()
        self.initUI()

    def initUI(self):
        self.lightsBtn = QPushButton('Turn On')
        self.lightsBtn.setCheckable(True)  
        self.lightsBtn.setStyleSheet("QPushButton:checked {color: white; background-color: green;}")
        self.lightsBtn.clicked.connect(self.lightsBtnHandler)

        self.setCentralWidget(self.lightsBtn)

    def lightsBtnHandler(self):
        if self.lightsBtn.isChecked():
            self.startLightsThread()
        else:
            self.stopLightsThread()

    def startLightsThread(self):
        print 'start lightsThread'
        self.lightsThread = QThread()
        self.lightsWorker = LightsWorker()
        self.lightsWorker.moveToThread(self.lightsThread)
        self.lightsThread.started.connect(self.lightsWorker.work)
        self.lightsThread.start()


    def stopLightsThread(self):
        print 'stop lightsThread'
        self.lightsWorker.stop()



class LightsWorker(QObject):
    signalFinished = pyqtSignal()

    def __init__(self):
        QObject.__init__(self)
        self._mutex = QMutex()
        self._running = True

    @pyqtSlot()
    def work(self):
        while self._running:
            print 'working'
            time.sleep(1)
        self.signalFinished.emit()

    @pyqtSlot()
    def stop(self):
        print 'Stopping'
        self._mutex.lock()
        self._running = False
        self._mutex.unlock()



app = QApplication(sys.argv)
window = Screen()
window.show()
sys.exit(app.exec_())
+4
source share
2 answers

after the answer fooobar.com/questions/686766 / ... after stopping lightWorkeryou should exit the stream and wait until it stops

def stopLightsThread(self):
    print('stop lightsThread')
    self.lightsWorker.stop()
    self.lightsThread.quit()
    self.lightsThread.wait()
+4
source

I had to face the same problem in C ++, but the problem is the same.

, QThread , . , , .

:

  • ()
  • ressource ( , / QObject)
  • ,

.

, . python, , , .

, :

  • , " "
  • : "exit" , .
  • , .

optionnal: ressources , , , , .

, : .

QtConcurrent.

+2

Source: https://habr.com/ru/post/1675458/


All Articles