qgis – Custom Python Expression Function Defined as Macro Guide

expressionmacropyqgisqgis

Is it possible to define a custom Python Expression function like in the project macros?

Each time when I try to enable the macros and write any code, I get a security warning saying that Python macros cannot currently be run (as in the attached pictures).

enter image description here

enter image description here

I get a crash when attempting to run the last screenshot scenario.

Best Answer

You can create a custom expression function in a macro in this way:

enter image description here

Sample code:

from qgis.utils import qgsfunction
from qgis.core import QgsExpression

@qgsfunction(args='auto', group='test', referenced_columns=[])
def my_sum(value1, value2, feature, parent):
    return value1 + value2

def openProject():
    pass

def saveProject():
    pass

def closeProject():
    QgsExpression.unregisterFunction('my_sum')

Note we unregister the created function when closing the project.

Therefore, the function my_sum() will only be available while your project is open, if the user accepts macros in her/his QGIS session.


Due to security issues that macros could trigger, your users will be asked for confirmation on running your macro, unless they have set the Enable macros option to Always (Not Recommended) in Settings --> Options... --> General.

Related Question