One of my projects has a layer label that is calculated by an expression from seven field values as follows:
if(coalesce("caption" ,'') = '', '', "caption" || '\n') || trim(concat("Distance",' ', "Unit", ' ', "Label", ' ',"Distance 2",' ', "Unit 2", ' ',"Label 2", ' '))
I want to replace this with a custom function in order to do some additional processing without writing a very complex expression.
Using the function editor I have put this custom function in.
from qgis.core import *
from qgis.gui import *
@qgsfunction(args='auto', group='Custom')
def loclabels(capt, dist1,unit1,label1,dist2,unit2,label2, feature, parent):
cap=coalesce(capt,'')
cap2 = trim(dist1 + ' ' + unit1 + ' ' + label1 + ' ' + dist2 + ' ' + unit2 + ' ' + label2)
if cap == '':
fullcapt = cap2
else:
if cap2 != '':
fullcapt = cap + '\n' + cap2
else:
fullcapt = cap
return fullcapt
Calling this and passing the same fields as the original expression always returns a null value. In fact even trying to return a constant returns a null. The function is syntactically correct (no errors in the code) but simply fails to return any useful data.
What is missing?
coalesce
andtrim
aren't Python functions. Custom functions are Python so you will have to use what is usable there.