How can I create a new group in the layer manager using python code?
2 Answers
Adding groups to the Layers Panel
Using the new Layer tree (introduced since QGIS v.2.4 and available for QGIS v3.x) you can add a group to the QGIS ToC this way:
root = QgsProject.instance().layerTreeRoot()
myGroup1 = root.addGroup("My Group 1")
If you want to add it to a particular position in the ToC, use:
myGroup1 = root.insertGroup(2, "My Group 1")
Adding groups into other groups
You can even create nested groups (a group into a group):
myGroupA = myGroup1.addGroup("My Group A")
If you need to first find an existing group where to put your new group, use this:
myOriginalGroup = root.findGroup("My existing group") # We assume the group exists
myNewGroup = myOriginalGroup.addGroup("My New Group")
-
-
1Layer tree, legend, ToC, they are names normally used in GIS when refering to the list of layers and groups in a software. Commented Dec 7, 2017 at 13:51
There is the method QgsLegendInterface.addGroup( name, expand, parent )
Example:
iface.legendInterface().addGroup( 'abc')
-
Thank you very much, the problem was that I did not refer to the interface and used directly QgsLegendInterface.addGroup Commented Jul 16, 2013 at 11:54
-
Is there any way to control the position where you insert the menu? The menu is inserted under the shape you have selected. I need to put it above all layers. Thanks. Commented Jul 17, 2013 at 5:35
-