bobbay
bobbay

Reputation: 493

Cannot get qthread example to work

I am totally stuck with this python qt threading tutorial. I have two issues.

1) The longRunning function never executes. 2) When exiting the app, I get QThread: Destroyed while thread is still running and a Python.exe has stopped working.

Any help? Thanks!!

#!/usr/bin/env python2

import sys, time
from PySide.QtGui import *
from PySide import QtCore


class SeperateThread(QtCore.QObject):
    finished = QtCore.Signal()

    def __init__(self, parent = None):
        super(SeperateThread, self).__init__(parent)
        self._isRunning = True

    def longRunning(self):
        end = time.time()+3
        while self._isRunning == True:
            sys.stdout.write('*')
            sys.stdout.flush()
            time.sleep(1)
            now = time.time()
            if now>=end:
                self._isRunning=False
        self.finished.emit()

    def stop(self):
        self._isRunning = False


class MainWindow(QMainWindow):
        def __init__(self, parent=None):
                QMainWindow.__init__(self,parent)
                centralwidget = QWidget(self)
                startButton = QPushButton('Start long (3 seconds) operation',self)
                label2 = QLabel('Long batch')
                vbox = QVBoxLayout()
                vbox.addWidget(startButton)
                vbox.addWidget(label2)
                self.setCentralWidget(centralwidget)
                centralwidget.setLayout(vbox)

                obj = SeperateThread()
                objThread = QtCore.QThread()
                obj.moveToThread(objThread)
                objThread.started.connect(obj.longRunning)    

                def LongOperationStart():
                        label2.setText('app is running')
                        startButton.setEnabled(False)
                        objThread.start()

                def LongOperationFinish():
                        startButton.setEnabled(True)

                #GUI start button
                startButton.clicked.connect(LongOperationStart)

                #Once thread is finished. 
                objThread.finished.connect(LongOperationFinish)

                obj.finished.connect(objThread.quit)


if __name__=='__main__':
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())

Upvotes: 0

Views: 157

Answers (1)

bobbay
bobbay

Reputation: 493

Oh ok, I found out what I was doing wrong:

SeperateThread is being garbage collected after the MainWindow constructor returns. Make obj a member of MainWindow so that it persists beyond the constructor.

Thanks!!

Upvotes: 2

Related Questions