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).
I get a crash when attempting to run the last screenshot scenario.
-
1On the right of the security warning there is an "Enable Macro" link did you try to click on that ? Also on the QGIS option (General tab) what is the status of the "Enable macros" setting ?J.R– J.R2021年11月29日 11:14:09 +00:00Commented Nov 29, 2021 at 11:14
-
In the first case ("Hello I am a macro" example) there is an error QgsMessangerBar.INFO . Once I deleted it the macro will work but the warning it will still appear. Whereas in the second case (with that function), the QGIS crashes when I click on "Enable Macro" link. The Enable macros is set to "Ask". Should it be set to "Always"? What I am actually trying to do is to define in the macros a "Custom Python expression function" like to use it in the forms of the project.NEM– NEM2021年11月29日 11:52:35 +00:00Commented Nov 29, 2021 at 11:52
1 Answer 1
You can create a custom expression function in a macro in this way:
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
.
-
Is the function automatically registered?Noura– Noura2021年11月29日 19:57:32 +00:00Commented Nov 29, 2021 at 19:57
-
Yes, as soon as QGIS finds the
@qgsfunction
decorator, QGIS knows that's a function ready to be registered, and proceeds with its registration.Germán Carrillo– Germán Carrillo2021年11月29日 20:33:09 +00:00Commented Nov 29, 2021 at 20:33 -
Thank you! It works indeed. I did not find this in the documentation. I wonder how you know about it.NEM– NEM2021年12月06日 12:26:33 +00:00Commented Dec 6, 2021 at 12:26
-
1Well, there are lots of things you know by practicing and by attempting alternate solutions. I've been working with PyQGIS since 2009! So, that's the secret :)Germán Carrillo– Germán Carrillo2021年12月10日 00:03:03 +00:00Commented Dec 10, 2021 at 0:03