简体   繁体   中英

PyQt4 QThread / moveToThread not working depending on context?

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

Thanks in Advance for any help!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM