Skip to content

Commit

Permalink
Add simple python method QgsTask.fromFunction for creation of tasks
Browse files Browse the repository at this point in the history
from a function without having to create a QgsTask subclass
  • Loading branch information
nyalldawson committed Dec 5, 2016
1 parent e29dd79 commit 5d46892
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions python/core/__init__.py
Expand Up @@ -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.