Skip to content
Permalink
Browse files
Add simple python method QgsTask.fromFunction for creation of tasks
from a function without having to create a QgsTask subclass
  • Loading branch information
nyalldawson committed Dec 5, 2016
1 parent e29dd79 commit 5d4689294dffa9d6a58851bc2b087a8b64cb221e
Showing with 53 additions and 0 deletions.
  1. +53 −0 python/core/__init__.py
@@ -183,3 +183,56 @@ def __exit__(self, ex_type, ex_value, traceback):
else:
self.layer.rollBack()
return False


class QgsTaskException(Exception):

def __init__(self, msg):
self.msg = msg

def __str__(self):
return self.msg


class QgsTaskResult(Exception):

def __init__(self, r):
self.r = r

def result(self):
return self.r


class QgsTaskWrapper(QgsTask):

def __init__(self, description, function, *extraArgs):
QgsTask.__init__(self, description, QgsTask.ProgressReport)
self.extraArgs = extraArgs
self.function = function
self.task_result = None
self.task_error = None

def run(self):
try:
for status in self.function(*self.extraArgs):
self.setProgress(status)
except QgsTaskException as e:
self.task_error = e.msg
self.stopped()
except QgsTaskResult as r:
self.task_result = r.result()
self.completed()
else:
self.completed()

def result(self):
return self.task_result

def error(self):
return self.task_error


def fromFunction(cls, description, function, extraArgs):
return QgsTaskWrapper(description, function, extraArgs)

QgsTask.fromFunction = classmethod(fromFunction)

0 comments on commit 5d46892

Please sign in to comment.