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?