How to move an object back and forth between QThre

2019-04-14 05:43发布

问题:

In my program (using Python 2.7), I create an object containing some important data and methods. Some of the methods are CPU hungry, so in certain cases I move the object to a new QThread for the duration of the CPU intensive methods, then have them come back to the main thread. At a later point, when a CPU intensive method is called, I would like to move the object to another QThread again, however this fails saying "Current thread is not the object's thread".

Here is a trivial example which reproduces the problem:

import sys
from PyQt4 import QtCore, QtGui
from time import sleep

class ClassA(QtGui.QDialog):
    def __init__(self):
        super(ClassA, self).__init__()
        mainLayout=QtGui.QVBoxLayout()
        self.lineEdit=QtGui.QLineEdit()
        mainLayout.addWidget(self.lineEdit)
        self.setLayout(mainLayout)
        self.show()
        self.obj=ClassC(self)        
        self.executeProgram()
    def executeProgram(self):
        self.lineEdit.setText("Starting new thread...")
        self.thread=QtCore.QThread()
        self.obj.moveToThread(self.thread)        
        self.thread.started.connect(self.obj.doWork)
        self.obj.doingWork.connect(self.updateGui)
        self.obj.finished.connect(self.killThread)
        self.thread.start()
    def updateGui(self,message):
        self.lineEdit.setText(message)
    def killThread(self):
        self.thread.quit()
        self.thread.wait()
        self.obj.finished.disconnect()
        self.executeProgram()

class ClassC(QtCore.QObject):
    finished=QtCore.pyqtSignal()
    doingWork=QtCore.pyqtSignal(str)
    def __init__(self,parent=None):
            super(ClassC, self).__init__()
    def doWork(self):
        for i in range(5):
            self.doingWork.emit("doing work: iteration "+str(i))
            sleep(1)
        self.finished.emit()

if __name__=="__main__":
    app=QtGui.QApplication(sys.argv)
    obj=ClassA()
    app.exec_()       

Is it possible to move an object to a different QThread multiple times? If so, how would I fix my code to do this?

回答1:

Note moveToThread must be called on the thread that the object currently belongs to, so you may need to move the object back to the main thread before moving it to yet another thread.

Add the line mainThread = QtCore.QThread.currentThread() somewhere at the top, and put self.moveToThread(mainThread) right before emitting the finished signal.