napari.qt.threading.FunctionWorker
-
class
napari.qt.threading.FunctionWorker(func, *args, **kwargs)[source]¶ Bases:
napari._qt.qthreading.WorkerBaseQRunnable with signals that wraps a simple long-running function.
Note
FunctionWorkerdoes not provide a way to stop a very long-running function (e.g.time.sleep(10000)). So whenever possible, it is better to implement your long running function as a generator that yields periodically, and use theGeneratorWorkerinstead.- Parameters
func (Callable) – A function to call in another thread
*args – will be passed to the function
**kwargs – will be passed to the function
- Raises
TypeError – If
funcis a generator function and not a regular function.
Methods
autoDelete(self)create(Callable[[], None])quit()Send a request to abort the worker.
run()Start the worker.
setAutoDelete(self, bool)start()Start this worker in a thread and add it to the global threadpool.
work()Main method to execute the worker.
Attributes
Whether the worker has been requested to stop.
Whether the worker has been started
Details
-
create(Callable[[], None]) → QRunnable¶
-
quit()¶ Send a request to abort the worker.
Note
It is entirely up to subclasses to honor this method by checking
self.abort_requestedperiodically in theirworker.workmethod, and exiting ifTrue.- Return type
None
-
run()¶ Start the worker.
The end-user should never need to call this function. But it cannot be made private or renamed, since it is called by Qt.
The order of method calls when starting a worker is:
calls QThreadPool.globalInstance().start(worker) | triggered by the QThreadPool.start() method | | called by worker.run | | | V V V worker.start -> worker.run -> worker.work
This is the function that actually gets called when calling
QThreadPool.start(worker)(). It simply wraps thework()method, and emits a few signals. Subclasses should NOT override this method (except with good reason), and instead should implementwork().
-
setAutoDelete(self, bool)¶
-
start()¶ Start this worker in a thread and add it to the global threadpool.
The order of method calls when starting a worker is:
calls QThreadPool.globalInstance().start(worker) | triggered by the QThreadPool.start() method | | called by worker.run | | | V V V worker.start -> worker.run -> worker.work
-
work()[source]¶ Main method to execute the worker.
The end-user should never need to call this function. But subclasses must implement this method (See
GeneratorFunction.work()for an example implementation). Minimally, it should checkself.abort_requestedperiodically and exit if True.Examples
class MyWorker(WorkerBase): def work(self): i = 0 while True: if self.abort_requested: self.aborted.emit() break i += 1 if i > max_iters: break time.sleep(0.5)