# -*- coding: utf-8 -*- """ *************************************************************************** __init__.py --------------------- Date : May 2014 Copyright : (C) 2014 by Nathan Woodrow Email : woodrow dot nathan at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from builtins import str from builtins import object __author__ = 'Nathan Woodrow' __date__ = 'May 2014' __copyright__ = '(C) 2014, Nathan Woodrow' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.PyQt.QtCore import QCoreApplication, NULL import inspect import string from qgis._core import * # Boolean evaluation of QgsGeometry def _geometryNonZero(self): return not self.isEmpty() QgsGeometry.__nonzero__ = _geometryNonZero QgsGeometry.__bool__ = _geometryNonZero def register_function(function, arg_count, group, usesgeometry=False, referenced_columns=[QgsFeatureRequest.AllAttributes], **kwargs): """ Register a Python function to be used as a expression function. Functions should take (values, feature, parent) as args: Example: def myfunc(values, feature, parent): pass They can also shortcut naming feature and parent args by using *args if they are not needed in the function. Example: def myfunc(values, *args): pass Functions should return a value compatible with QVariant Eval errors can be raised using parent.setEvalErrorString("Error message") :param function: :param arg_count: :param group: :param usesgeometry: :return: """ class QgsExpressionFunction(QgsExpression.Function): def __init__(self, func, name, args, group, helptext='', usesgeometry=True, referencedColumns=QgsFeatureRequest.AllAttributes, expandargs=False): QgsExpression.Function.__init__(self, name, args, group, helptext, usesgeometry, referencedColumns) self.function = func self.expandargs = expandargs def func(self, values, context, parent): feature = None if context: feature = context.feature() try: if self.expandargs: values.append(feature) values.append(parent) return self.function(*values) else: return self.function(values, feature, parent) except Exception as ex: parent.setEvalErrorString(str(ex)) return None helptemplate = string.Template("""