2

I'm not sure if this is even possible in QGIS, but I try to filter features in a layer based on the names of visible layers within a certain group.

Example: I have a group holding layers named by different countries. In another layer, e.g. called stations, I have an attribute called "country" which I want to filter by the names of countries which are toggled on (visible) in the group. So if I display the layers Germany and Italy in the group, the stations layer will be filtered automatically by Germany and Italy.

1
  • As far as I know, layer groups (this is what you mean by groups, right?) can't be addressed with QGIS expressions. Otherwise, it would be easy to use QGIS expressions. I guess you should do it using Python.
    – Babel
    Commented Aug 29 at 9:25

2 Answers 2

1

You can use the expression is_layer_visible(layer) for the filter (or a rule-based symbolisation). If you have an attribute in the station layer that contains the name of the country layer, you can use this as the layer name in the expression and therefore only need one rule.

1

Thanks @Babel. I think I found a solution to my question by writing a custom function in python:

@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

I use this function in a ruled-based symbology of another layer by calling FIELD_1 IN (my_filter(<group name>)). It works perfectly when only one layer is set visible in the layer group. 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 seperated string and removed the quotes at the start and end of the string to get the same format as when typing a filter with strings manually. But it doesn't work. Any suggestions what I'm doing wrong?

1

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.