0

I have a pretty long expression filter so it would be more neat to put it all in a function expression instead. So far, I just found that equivalent PyQGIS within function body tends to be ironically even longer, though.

I'm trying to find equivalent expression in PyQGIS of

attribute(@atlas_feature, 'FIELD_NAME')

1 Answer 1

1

The @atlas_feature is a variable which is provided in the expression context from the environment. Such variables are normally passed as parameters into functions, just like you are passing it here as a parameter to a function attribute.

You can do the same in your own function which then looks like this:

@qgsfunction(args=1, group='shorthands')
def get_atlas_attribute(atlasfeature, feature, parent):
    return atlasfeature['FIELD_NAME']

And you would call it like this

get_atlas_attribute(@atlas_feature)

I am not sure if this is of big help for you just as well as I am not sure what exactly you want to achieve.

I guess it's mostly about making your expressions more readable by delegating repeated code to a dedicated function. I think that's fine (although it adds another layer of potential failures).

I just found that equivalent PyQGIS within function body tends to be ironically even longer

That is very likely to be true. And I don't think there is anything ironic about it. The expression engine is built for this very purpose. Take yet another language and you will have even more code ;)

6
  • Can I have like get_atlas_attribute()? I'd like that expression function figure @atlas_feature out on its own. Is it possible?
    – sandthorn
    Commented Aug 31, 2016 at 17:07
  • Possibly yes, based on the register_function code but overwriting funcV2 instead of func where you get a expression context instead of a feature as parameter. Commented Aug 31, 2016 at 20:20
  • Okey. I'd like to pass @atlas_feature more than any deeper route then. Anyway, I've still not got what it is supposed to. atlasfeature['FIELD_NAME'] Eval Error: list indices must be integers, not str It looks like expression calculator sees atlasfeature as some kind of collections. Is atlasfeature passed down here actually QT.Variant? (seen on other questions) If so, how do I cast it back as a QGIS feature?
    – sandthorn
    Commented Sep 1, 2016 at 4:32
  • I guess I'm getting closer but still not there. QgsFeature(atlasfeature).attribute('FIELD_NAME') Eval Error: 'FIELD_NAME' This leaves me stoned. What's next to do then?
    – sandthorn
    Commented Sep 1, 2016 at 5:22
  • Sidenote: this will be much easier with QGIS 3, where the expression context is always there ;) Does atlasfeature[0]['FIELD_NAME'] work? Commented Sep 1, 2016 at 5:22

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.