Skip to content

Commit 5d46892

Browse files
committed
Add simple python method QgsTask.fromFunction for creation of tasks
from a function without having to create a QgsTask subclass
1 parent e29dd79 commit 5d46892

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

python/core/__init__.py

+53
Original file line numberDiff line numberDiff line change
@@ -183,3 +183,56 @@ def __exit__(self, ex_type, ex_value, traceback):
183183
else:
184184
self.layer.rollBack()
185185
return False
186+
187+
188+
class QgsTaskException(Exception):
189+
190+
def __init__(self, msg):
191+
self.msg = msg
192+
193+
def __str__(self):
194+
return self.msg
195+
196+
197+
class QgsTaskResult(Exception):
198+
199+
def __init__(self, r):
200+
self.r = r
201+
202+
def result(self):
203+
return self.r
204+
205+
206+
class QgsTaskWrapper(QgsTask):
207+
208+
def __init__(self, description, function, *extraArgs):
209+
QgsTask.__init__(self, description, QgsTask.ProgressReport)
210+
self.extraArgs = extraArgs
211+
self.function = function
212+
self.task_result = None
213+
self.task_error = None
214+
215+
def run(self):
216+
try:
217+
for status in self.function(*self.extraArgs):
218+
self.setProgress(status)
219+
except QgsTaskException as e:
220+
self.task_error = e.msg
221+
self.stopped()
222+
except QgsTaskResult as r:
223+
self.task_result = r.result()
224+
self.completed()
225+
else:
226+
self.completed()
227+
228+
def result(self):
229+
return self.task_result
230+
231+
def error(self):
232+
return self.task_error
233+
234+
235+
def fromFunction(cls, description, function, extraArgs):
236+
return QgsTaskWrapper(description, function, extraArgs)
237+
238+
QgsTask.fromFunction = classmethod(fromFunction)

0 commit comments

Comments
 (0)