Before I run my code, I need to move the focus to a group in my layer tree. I managed to do it with a layer:
registry = QgsProject.instance() layer = registry.mapLayersByName("LayerName") iface.setActiveLayer(layer)
but there doesn't seem to be a similar method for groups, like
group = root.findGroup ('groupName') iface.setActiveGroup(group)
How is this accomplished?
I have tried to use this code:
#Moving the 4 layers generated by the model to the group "QS" ModelTuple = ("Cirlces", "Border 1", "Border 2", "Trees") for itm in ModelTuple: try: layer = QgsProject.instance().mapLayersByName(itm) root = QgsProject.instance().layerTreeRoot() mylayer = root.findLayer(layer.id()) myClone = mylayer.clone() parent = mylayer.parent() group = root.findGroup("QS") group.insertChildNode(0, myClone) parent.removeChildNode(mylayer) except: print("Error: "+ itm) continue
it works perfectly fine in a new blank project. But when the code is executed in my already created project with several groups and layers, 2 of the layers from the model can't be cloned, for some reason, error message:
AttributeError: 'NoneType' object has no attribute 'clone'
so I decided to go a different way: not move the 4 layers to the group "QS", but instead choose the right place in the layer tree before hand and leave the layers right there.