Martin Schulze
Martin Schulze

Reputation: 2171

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!

Upvotes: 0

Views: 1059

Answers (1)

Martin Schulze
Martin Schulze

Reputation: 2171

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

Upvotes: 1

Related Questions