I would like to programmatically filter a layer based on its attributes and then export this filtered layer to KML file. In the example below, I have a layer called 'conduit' that I attempt to filter where status = AB
. I then try to export this filtered layer to KML file. When I run the export, the full, unfiltered layer is exported.
def get_layer_by_name_quick(namepattern):
layers = []
for lyr in QgsProject.instance().mapLayers().values():
if namepattern in str(lyr.name()):
layers.append(lyr)
if len(layers) == 0:
print(f"No Layer named : {namepattern}")
return None
elif len(layers) > 1:
print(f"multiple layers returned: \nnamepattern: {namepattern}, \nlayers: {layers}\n")
return layers[0]
else:
return layers[0]
# get the layer named conduit
conduit_layer = get_layer_by_name_quick('CONDUIT')
# filter the layer for status = AB
expression = "status = 'AB'"
conduit_layer.setSubsetString(expression)
# write the output to kml file
output_layer = r"C:\path\to\file\file.kml"
QgsVectorFileWriter.writeAsVectorFormat(conduit_layer, output_layer, "utf-8", conduit_layer.crs(), "KML")
In fact, when I try to filter the layer via conduit_layer.setSubsetString(expression)
, I do not see the changes reflected in the map canvas. I would expect to see a filter symbol next to the layer name in the table of contents indicating that it is being filtered and I would expect to the see only the "AB status" conduit displayed on the map.
This is not what occurs. conduit_layer.setSubsetString(expression)
returns a value of "True" and does not provide a handle that I can use to reference the filtered layer after the query is run.
How do I filter a layer based on attributes and then export the filtered result to a KML file?
Can you provide any additional information on how to specify the layer attributes during the export process?
For example, I'd like to be able to specify that no attributes are saved during the export to KML or I would like to specify a few by their field name if possible. The documentation has not helped me resolve this yet. From QGIS exporting attributes in a KML file I understand there is a way to do this using the GUI, but I am looking to do it via Python.
The code above actually works. I mistakenly thought it was not exporting the filtered layer, but after comparing to an export done via the GUI, the result is the same and the exported layer is indeed filtered.