Repository navigation
Expand file tree
/
Copy pathworkers.py
More file actions
47 lines (36 loc) · 1.54 KB
/
Copy pathworkers.py
File metadata and controls
47 lines (36 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Qt worker helpers for non-blocking application operations."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from PySide6.QtCore import QObject, QRunnable, Signal, Slot
class WorkerSignals(QObject):
result = Signal(object)
error = Signal(object)
progress = Signal(int, int)
finished = Signal()
class Worker(QRunnable):
"""Run a callable in QThreadPool and emit results on the GUI thread.
Callers that connect plain functions or lambdas must pass
``Qt.ConnectionType.QueuedConnection``: with no receiver QObject, Qt
invokes such slots directly on the worker thread, which would touch the
GUI from outside the main thread.
Extra keyword arguments are forwarded to the callable, which is how a long
running function receives a ``progress(bytes_done, bytes_total)`` reporter:
workers that need it are built first and get ``kwargs["progress"]`` bound to
``signals.progress.emit``.
"""
def __init__(self, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
super().__init__()
self.setAutoDelete(True)
self.function = function
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
@Slot()
def run(self) -> None:
try:
self.signals.result.emit(self.function(*self.args, **self.kwargs))
except Exception as exc: # forwarded and rendered on the GUI thread
self.signals.error.emit(exc)
finally:
self.signals.finished.emit()