2

I would like to save all layers that are part of a preset in QGIS to an external folder using Python

I have got the following code from another question

from qgis.core import *

suffix = "_Test_save"
pathToFile = "C:/Users/david/Desktop/Batch Vector Save testing Python/"

layers = iface.legendInterface().layers()

for layer in layers:
    newName = layer.name() + suffix + ".shp"
    ret = QgsVectorFileWriter.writeAsVectorFormat(layer, pathToFile + newName, "utf-8", None, "ESRI Shapefile")
    if ret == QgsVectorFileWriter.NoError:
        print newName + " saved to " + pathToFile + "!"

This saves all layers in the workspace to my chosen folder but I cannot figure a way to save only the visible layers or even just ones attached to a preset.

This is working code for QGIS2.18 but if possible I would like a solution for QGIS3.

2

The preset collections have been renamed and bundled into the QgsMapThemeCollection class so for QGIS 3, you could use something like the following which saves all visible layers of a theme to your desired output directory:

suffix = "_Test_save"
pathToFile = "C:/Users/david/Desktop/Batch Vector Save testing Python/"

layer_list = QgsProject.instance().mapThemeCollection().mapThemeVisibleLayers(u'theme_Name')
for layer in layer_list:
    newName = layer.name() + suffix + ".shp"
    QgsVectorFileWriter.writeAsVectorFormat(layer, pathToFile + newName, "UTF-8", layer.crs(), "ESRI Shapefile")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.