4

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?

1
  • 3
    coalesce and trim aren't Python functions. Custom functions are Python so you will have to use what is usable there.
    – Nathan W
    Commented Nov 7, 2017 at 5:52

1 Answer 1

2

You can try :

cap = capt if capt is not None else ''

instead of :

cap=coalesce(capt,'')

and :

cap2 = (dist1 + ' ' + unit1 + ' ' + label1 + ' ' + dist2 + ' ' + unit2 + ' ' + label2).strip()

instead of :

cap2 = trim(dist1 + ' ' + unit1 + ' ' + label1 + ' ' + dist2 + ' ' + unit2 + ' ' + label2)

Also you might test your function in the python console (removing the expression extra stuff) before using it in an expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.