QGIS & Python – How to Apply a Filter to Multiple Vector Layers

filterpyqgispythonqgisquery

I am trying to apply an attribute filter to multiple layers in QGIS at once. The filter is to be applied to .osm data brought in through PostGIS to QGIS.

I have tried selecting multiple layers -> right-click –> filter but it only applies it to the last layer I selected of the group. I want to be able to apply a filter through a query like "osm_user" = 'donlaser' to multiple layers at once, rather than having to repeat the process many times.

Is there a standard way to do this within QGIS that I am missing? Is there a plugin that would provide this functionality?

A Python-based solution would also be useful for me.

Best Answer

This is how I'd do it with PyQGIS:

In your QGIS ToC, turn off those layers that you want to keep untouched, i.e., leave visible only the layers you want to set the filter to.

Now open a QGIS Python console and paste this code:

layers = iface.mapCanvas().layers()
for layer in layers:
    layer.setSubsetString('"osm_user" = \'donlaser\'')

This should do the trick.