PyQGIS Expression – Resolving Unrecognized Geometry Methods in QGIS Expression Field Calculator

pyqgisqgis-3qgis-expression

It appears as though the function editor on the Field Calculator is not recognizing the Geometry() method on the feature.

Example code below, always returns -1 into the field I populate from the Field Calculator. The features have valid geometry. The source table is standalone and not a join.
When I also do a print(geometry()) call, it returns <QgsGeometry: null>
The weird thing is that on the Field Calculator preview, it shows the correct value.

The issue is similar to this issue:

Expression not saving in QGIS Field Calculator?

However the tables I am working with have no joins. I have tested on both 3.18 and 3.22 versions with a blank project. No joins/relationships.

from qgis.utils import qgsfunction
from qgis.core import *
from qgis.gui import *
    
@qgsfunction(args='auto', group='Custom')
    
def test_geom(feature, parent):
    
    area_calc = feature.geometry().area()
        
    return area_calc

enter image description here

Best Answer

Seriously, I've had this problem all day, scouring google, 10 minutes after posting the question - of course, I stumble across the answer on the git forums.

The reason why this doesn't work is explained in detail here https://github.com/qgis/QGIS/issues/41695

In short, the Preview doesn't use the same code as the actual function method, and in order to get it to work, you need to declare usesgeometry=True in the function declaration.

So this works.

from qgis.utils import qgsfunction
from qgis.core import *
from qgis.gui import *
    
@qgsfunction(args='auto', group='Custom', usesgeometry=True)
    
def test_geom(feature, parent):
    
    area_calc = feature.geometry().area()
        
    return area_calc
Related Question