I would like to copy all visible layers in a project to a new group. Does anyone know of a quick way of doing this?

Background: We have a Project that acts as a library for all the spatial data we hold.

When creating output-oriented Projects, we identify the data required in the library, copy it to a new Group and then that new Group becomes the basis of the new Project. Being able to batch copy all visible (displayed) layers to the new group would massively speed up the new Project generation process and keep the workflow (and datasets) clean and simple.

  • 2
    Obviously this could be achieved manually, so the assumption is that you are wanting some kind of script, or ability to write a script to perform this based on visible layers? – nr_aus Sep 16 '20 at 2:00

Use the following script.

root = QgsProject.instance().layerTreeRoot()
group = root.addGroup("group")

for layer in root.children():
   if layer.isVisible() and layer != group:
       _layer = layer.clone()

enter image description here

Note: If there is another visible group layer including visible/invisible layers, that group layer is copied with its all layers to new group layer.

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.