PyQt4 QThread/moveToThread不能根据上下文工作? [英] PyQt4 QThread / moveToThread not working depending on context?

查看:65
本文介绍了PyQt4 QThread/moveToThread不能根据上下文工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么以下代码立即退出,但是如果我在主上下文而不是第二个对象中创建线程,则可以正常工作吗?

I'm trying to understand why the following code immediately exits, but works if I create the thread in the main context and not in a second object?

from PyQt4 import QtCore
import time
import sys

class SomeObject(QtCore.QObject):

    finished = QtCore.pyqtSignal()

    def longRunning(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print "Increasing"
            count += 1
        self.finished.emit()

class SecondObject(QtCore.QObject):
    def __init__(self, app):
        QtCore.QObject.__init__(self)
        objThread = QtCore.QThread()
        obj = SomeObject()
        obj.moveToThread(objThread)
        obj.finished.connect(objThread.quit)
        objThread.started.connect(obj.longRunning)
        objThread.finished.connect(app.exit)
        objThread.start()

def usingMoveToThread():
    app = QtCore.QCoreApplication([])
    SecondObject(app)
    sys.exit(app.exec_())

if __name__ == "__main__":
    usingMoveToThread()

在此先感谢您的帮助!

推荐答案

我发现了问题.显然,您需要保留新线程的引用,否则应用程序将退出...

I've found the problem. Apparently you need to hold on to the new Thread's reference otherwise the Application will just quit...

这篇关于PyQt4 QThread/moveToThread不能根据上下文工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆