PyQt4 QThread / moveToThread根据上下文不起作用?

时间:2013-01-04 11:10:58

标签: python multithreading pyqt pyqt4

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

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()

在预先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我发现了问题。显然你需要坚持新的Thread的参考,否则应用程序将退出...