[Python] Signal declaration in a separate class for use with QRunnable worker

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm defining a Qt signal in a separate class derived from QObject for use in a QRunnable worker. The signal is emitted once by the worker as it completes. When creating two workers, the signal is received twice for each workers (hence received 4 times, if there were 3 workers, the signal would be received 9 times, etc.).

    E.g. using the code below on two workers with IDs 3419 and 45435, the output is:

    complete: 3419
    complete: 3419
    complete: 45435
    complete: 45435


    I suspect the signal is not correctly defined in the separate class.

    import time, uuid
    from qtpy.QtCore import QObject, QThreadPool, QRunnable, Signal
    from qtpy.QtWidgets import QApplication, QMainWindow, QPushButton

    class MainWindow(QMainWindow):
    def __init__(self):
    super().__init__()
    self.button = QPushButton("Start 2 workers")
    self.button.pressed.connect(self.start)
    self.setCentralWidget(self.button)
    self.worker_manager = WorkerManager()

    def start(self):
    for i in range(2):
    worker = Worker()
    self.worker_manager.enqueue(worker)

    class Signals(QObject):
    complete = Signal(int)

    class Worker(QRunnable):
    signals = Signals()

    def __init__(self):
    super().__init__()
    self.worker_id = uuid.uuid4().time_mid

    def run(self):
    time.sleep(0.01)
    self.signals.complete.emit(self.worker_id)

    class WorkerManager(QObject):

    def __init__(self):
    super().__init__()
    self.threadpool = QThreadPool()

    def enqueue(self, worker):
    worker.signals.complete.connect(self.complete)
    self.threadpool.start(worker)

    def complete(self, worker_id):
    print('complete:', worker_id)

    def main():
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()

    if __name__ == '__main__':
    main()

    Continue reading...

Compartilhe esta Página