class napari.qt.threading.FunctionWorker(func, *args, **kwargs)[source]

Bases: napari._qt.qthreading.WorkerBase

QRunnable with signals that wraps a simple long-running function.

Note

FunctionWorker does 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 the GeneratorWorker instead.

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 func is a generator function and not a regular function.

Methods

Attributes

property abort_requested

Whether the worker has been requested to stop.

Return type

bool

autoDelete(self)bool
create(Callable[[], None])QRunnable
property is_running

Whether the worker has been started

Return type

bool

quit()

Send a request to abort the worker.

Note

It is entirely up to subclasses to honor this method by checking self.abort_requested periodically in their worker.work method, and exiting if True.

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 the work() method, and emits a few signals. Subclasses should NOT override this method (except with good reason), and instead should implement work().

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 check self.abort_requested periodically 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)