3

I want to use the following custom function in a ruled-based symbology of a layer to filter features by the names of visible layers within another layer group:

@qgsfunction(args='auto', group='Custom')
def my_filter(layer_group, feature, parent):
    root = QgsProject.instance().layerTreeRoot()
    my_group = root.findGroup(layer_group)
    layer_list = [layer.name() for layer in my_group.children() if layer.isVisible()]
    my_string = ','.join([f"'{i}'" for i in layer_list])[1:][:-1]
    return my_string

The function returns a comma-separated string with the according layer names, e.g. 'Layer 1', 'Layer 2', but when I try to use it in a filter expression by calling FIELD_1 IN (my_filter(<group name>)), it doesn't work correctly. As long as only one layer is set visible in the layer group, the filter is correct, however, when multiple layers are toggled on, the function fails.

I assume it has something to do with the format of the function result. I converted the list to a comma-separated string and removed the quotes at the start and end of the string to get the same format as when typing the string filter manually, e.g. FIELD_1 IN ('Layer1', 'Layer 2').

What am I doing wrong?

1 Answer 1

3

You can return the layer list instead of converting to a string and then adapt your syntax a little by using the array_contains function on the output in the expression.

@qgsfunction(args='auto', group='Custom')
def my_filter(layer_group, feature, parent):
    root = QgsProject.instance().layerTreeRoot()
    my_group = root.findGroup(layer_group)
    layer_list = [layer.name() for layer in my_group.children() if layer.isVisible()]
    
    # return the list of layers
    return layer_list

Expression

array_contains(my_filter('my group'), "FIELD_1")

enter image description here

3
  • Note, the field in the screenshot is called layer rather than FIELD_1
    – Matt
    Commented Sep 15 at 21:24
  • Great solution! Thanks a lot @Matt. One little thing: How do I make the feature count of my_layer displaying the number of actual visible points in the rule-based symbology? At the moment it is stuck at 0.
    – Calidris
    Commented Sep 16 at 6:08
  • Indeed, I experience the same. When the the visibility of layers is changed, the symbology updates, but the feature count sticks at its original value. Seems like a bug. If you deactivate and activate the rule with the checkbox in the settings, then it updates the count. Not handy to do every time, however.
    – Matt
    Commented Sep 19 at 7:57

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.