[PyQt] Re: Help with threads and signalling (Troy Unrau)

melkor at orangepalantir.org melkor at orangepalantir.org
Thu Jul 16 12:10:01 BST 2009


Ill offer an answer and a way to work around it, but maybe you'll get a
better one.

You are creating your timer in your new thread and you are killing it in
your main thread so to fix this you either need to create your timer in
your new thread, or you need to kill your timer in its own thread.

I solved this by putting an __init__ in the QThread that creates and
starts the timer.

mbs

I'm running some test code to get comfortable with signalling across
threads in PyQt4.

Basically, when I run it (PyQt4.5.2 for Python 2.6 on windows) I get the
error:
QObject::killTimer: timers cannot be stopped from another thread

Code pasted below, and attached (for whitespace preservation)

-- 
Troy Unrau, B.Sc.G.Sc.(Hons.)
Planetary Sciences Student - University of Western Ontario

'''
Testing threads in PyQt4

This program creates one thread in addition to the main GUI thread
which consists of a single shot timer that should shut down the
program after 10 second.

Alternatively, the program should be shut down if the user clicks on
"Quit" from the GUI before 10 seconds expires.  This should send a
signal to the thread's shutdown() slot, which stops the timer, and
the thread's event loop.

But it doesn't work - why?
'''

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class TestThread1(QThread):

    def run(self):
        self.timer = QTimer()
        self.timer.setInterval(10000)
        self.timer.setSingleShot(True)
        self.connect(self.timer, SIGNAL("timeout()"), self.timedout)
        self.connect(self.parent(), SIGNAL("clicked()"),
                     self, SLOT("shutdown()"), Qt.QueuedConnection)
        self.timer.start()

        self.exec_() # start threads' event loop

    # python "callable" slot
    def timedout(self):
        self.emit(SIGNAL("timeout()"))
        self.quit()

    @pyqtSlot()
    def shutdown(self):
        self.timer.stop()
        self.timedout()

def main():
    app = QApplication(sys.argv)

    w = QPushButton("Quit")

    thread1 = TestThread1(w)
    thread1.start()

    w.show()

    w.connect(thread1, SIGNAL("timeout()"), app, SLOT("quit()"))
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
-------------- next part --------------




More information about the PyQt mailing list