Every QgsFeature should have one corresponding parent layer, right? But there is no function to retrieve this layer?

Do I overlook something here?

@qgsfunction(args=0, group='Custom')
def getLayer(feature, parent): 
    layer = feature.layer()
    return layer

The expression function sample doesn't make much sense, but it shows my intention.

  • 3
    No, features have geometry and attributes. That's their definition in the QGIS world. They are objects that do not depend on layers. It is the vector layer that may have features or not. Apr 26 '20 at 12:00
  • Yes, that‘s what I have discovered. But most of the time a feature has a parent Layer. It wouldn‘t heart if feature.layer() would return None.
    – christoph
    Apr 26 '20 at 12:08
  • 2
    This question seems really similar to Getting parent layer of feature in QGIS PyQGIS Custom Function?
    – Jake
    Apr 26 '20 at 13:20
  • 2
    A "why" question is rarely suitable on this site, could you rephrase it? I am posting an answer for your actual problem in a moment. Nov 23 '21 at 10:43

I can't answer your question (the "why") but I can help you solve your problem.

It is currently not well documented but you can add another "magic" parameter to your function and that allows access to such information.

The Python expression function template says

 : param context: If there is an argument called ``context`` found at the last
                   position, this variable will contain a ``QgsExpressionContext``
                   object, that gives access to various additional information like
                   expression variables. E.g. ``context.variable( 'layer_id' )``

So for your example:

@qgsfunction(args="auto", group='Custom')
def get_layer_id(feature, parent, context): 
    layer_id = context.variable("layer_id")
    return layer_id

The layer would also be available but that is a C++ pointer, so I changed it to the ID in this example.

You can find the available variables if you open the "Variables" tree in the expression editor dialog.

  • Is this a feature of QGIS 3.23.x? Because in QGIS 3.22.0 (Windows) it doesn't work :-(
    – christoph
    Nov 23 '21 at 12:49
  • 2
    Sorry, I forgot to update the decorator to args="auto", then it should work! Nov 23 '21 at 12:55
  • 1
    thanks a lot, works like a charm now!
    – christoph
    Nov 23 '21 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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