I have a simple question about QThread. The attached simple example
illustrates a case where I have a widget that creates and holds a reference
to a thread, setting itself as the parent. I need the parent to hold a
reference to the thread, so I can interrupt its execution for example. I
want to delete the thread when it finishes executing.

What the script demonstrates is that when the widget catches the thread's
finished signal and deletes its reference to the thread, the thread
continues to persist until the widget itself goes out of scope. Is this due
to a cyclic reference? Can anyone suggest what I have done wrong, how I can
improve it?

Thank you,
Darren
import gc
import sys

from PyQt4 import QtCore, QtGui


class MyThread(QtCore.QThread):

    def __init__(self, parent):
        QtCore.QThread.__init__(self, parent)

    def run(self):
        for i in xrange(1000):
            print i
        print "I did my part!"

    def __del__(self):
        print "But the thread persisted until the widget went out of scope!"



class MyWidget(QtGui.QWidget):

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.thread = MyThread(self)
        self.thread.start()

        self.connect(
            self.thread,
            QtCore.SIGNAL("finished()"),
            self.processComplete
        )

    def processComplete(self):
        print 'got finished signal, attempting to delete thread...'
        self.thread = None
        gc.collect()


if __name__ == "__main__":
    myApp = QtGui.QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(myApp.exec_())
_______________________________________________
PyQt mailing list    PyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Reply via email to