5

I have a problem cloning more than one layer within a group. I am not proficient in PyQGIS by any stretch of the imagination. My task is to effectively duplicate all raster layers which names end with "_DEM", and append " copy" to the newly formed duplicates or clones. My code snippet for doing only one cloning is as follows:

names = [layer.name() for layer in QgsProject.instance().mapLayers().values()]
substring = "_DEM"
strings_with_substring = [name for name in names if substring in name]
print(strings_with_substring)

DEM = QgsProject.instance().mapLayersByName(strings_with_substring[0])[0]
duplicated = DEM.clone()
QgsProject.instance().addMapLayer(duplicated, False)
group.insertChildNode(3, QgsLayerTreeLayer(duplicated))

dname = duplicated.name()
duplicated.setName(dname + " copy")

Is there a way to construct a function or a loop to iterate this piece of code through every instance of the layer list i.e. strings_with_substring?

7

This should do the trick.

names = [layer.name() for layer in QgsProject.instance().mapLayers().values()]
substring = "_DEM"
strings_with_substring = [name for name in names if substring in name]
print(strings_with_substring)

for i in strings_with_substring :
    DEM = QgsProject.instance().mapLayersByName(i)[0]
    duplicated = DEM.clone()
    QgsProject.instance().addMapLayer(duplicated, False)
    group.insertChildNode(3, QgsLayerTreeLayer(duplicated))

    dname = duplicated.name()
    duplicated.setName(dname + " copy")

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.