QThread没有发出完成的信号

时间:2015-09-04 09:09:38

标签: python multithreading pyqt signals-slots qthread

我从另一个QThread运行QThread。第二个线程的finished信号未被发出。为什么呢?

from PyQt4 import QtGui, QtCore
import sys, time
thd, thd2 = None, None

class T(QtCore.QThread):
    def __init__(self, f):
        super().__init__()
        self.f = f
    def run(self):
        self.f()

def newThread(f, fin):
    t = T(f)
    t.finished.connect(fin)
    t.start()
    return t

def threadInThread():
    print("Run.")
    global thd2
    thd2 = newThread(lambda: print("Run2."), lambda: print("Fin2."))
    time.sleep(2)

class Form(QtGui.QWidget):
    def __init__(self):
        super().__init__()
        global thd
        thd = newThread(threadInThread, lambda: print("Fin."))

app = QtGui.QApplication(sys.argv)
f = Form()
f.show()
app.exec_()

1 个答案:

答案 0 :(得分:1)

将QThread对象移动到主线程(如果我们将finished连接到此对象的插槽)。

class T(QtCore.QThread):
    def __init__(self, f, finish=None):
        super().__init__()
        self.moveToThread(QtCore.QCoreApplication.instance().thread())
        self.f = f
        if finish:
            self.finish = finish
            self.finished.connect(self.onfinish)
    def onfinish(self):
        self.finish()
    def run(self):
        self.f()