Skip to content Skip to sidebar Skip to footer

Interrupting Qthread Sleep

I would like to know how to pause a QThread and then resume when I get a signal. I have read and know that I can do something like this: def run(self): ... self.ready=False

Solution 1:

You can do this pretty easily using the worker pattern of using QThreads. There's an example in the QThread documentation. The exact code will be a little different depending on whether you're using PyQt or PySide (it looks like you're using PySide from your example).

One notable issue with PySide compared to PyQt is that they didn't wrap QtCore.Q_ARG, so in PyQt, where you could normally use QMetaObject.invokeMethod to call a slot (with arguments) on the Worker object from the main thread, you can't do that directly in PySide and have to create a dummy signal (ie. Main.send_signal) to connect to the slot on the worker so you can call it from the main thread.

import time
import sys
from PySide import QtCore, QtGui


classWorker(QtCore.QObject):

    send_signal = QtCore.Signal(str) # using PySide# QtCore.pyqtSignal(str) ## using PyQt# @QtCore.pyqtSlot(str)    @QtCore.Slot(str)defreceive_slot(self, data):
        # data could be a filepath# open file# ... do stuff# close file
        QtCore.QThread.sleep(1) # to simulate doing stuff
        self.send_signal.emit(data + ' success')


classMain(QtGui.QWidget):

    send_signal = QtCore.Signal(str)

    def__init__(self):
        super(Main, self).__init__()
        self.worker = Worker()
        self.thread = QtCore.QThread(self)
        self.worker.moveToThread(self.thread)
        self.worker.send_signal.connect(self.receive_slot)
        self.send_signal.connect(self.worker.receive_slot)
        self.thread.start()
        self.send_signal.emit('Start')

    @QtCore.Slot(str)defreceive_slot(self, data):
        print'Main: {}'.format(data)
        self.send_signal.emit('Message {}'.format(time.time()))


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

Post a Comment for "Interrupting Qthread Sleep"