Emitting signals from a QRunnable

2020-07-27 02:52发布

问题:

I'm trying to send a signal from a QRunnable to my main QObject, but for some reason it isn't receiving them.

Is this the right way to do this?

Here's a small test case:

import sys

from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QThreadPool, QObject, QRunnable, pyqtSignal

class WorkerSignals(QObject):
    result = pyqtSignal(int)

class Worker(QRunnable):
    def __init__(self, task):
        super(Worker, self).__init__()

        self.task = task
        self.signals = WorkerSignals()

    def run(self):
        print 'Sending', self.task
        self.signals.result.emit(self.task)

class Tasks(QObject):
    def __init__(self):
        super(Tasks, self).__init__()

        self.pool = QThreadPool()
        self.pool.setMaxThreadCount(1)

    def process_result(self, task):
        print 'Receiving', task    # This does not run

    def start(self):
        for task in range(10):
            worker = Worker(task)
            worker.signals.result.connect(self.process_result)

            self.pool.start(worker)

        self.pool.waitForDone()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    stuff = Tasks()
    stuff.start()

回答1:

You need to call app.exec_()

When we call the application's exec_() method, the application enters the main loop. The main loop fetches events and sends them to the objects. Signals and slots are used for communication between objects. A signal is emitted when a particular event occurs. A slot can be any Python callable. A slot is called when a signal connected to it is emitted.

checkout Events and Signals in PyQt4