【问题标题】:QThread doesn't emit finished signalQThread 不发出完成信号
【发布时间】:2015-11-30 09:16:11
【问题描述】:

我从另一个 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_()

【问题讨论】:

  • 解释可能重复的答案:第二个QThreadfinished 信号连接在第一个QThread 内。这需要第一个 QThread 有一个正在运行的事件循环来处理信号,它没有因为您已经覆盖了调用 QThread.exec_()QThread.run() 的默认实现@
  • 嗯,moveToThread 有点帮助

标签: python multithreading pyqt signals-slots qthread


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多