13

How can I create a new group in the layer manager using python code?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
malagueff
  • 159
  • 2
  • 5

2 Answers2

34

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")

You can learn more on Layer tree handling here and here.

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
4

There is the method QgsLegendInterface.addGroup( name, expand, parent )

Example:

iface.legendInterface().addGroup( 'abc')
Matthias Kuhn
  • 27,780
  • 3
  • 88
  • 129
  • Thank you very much, the problem was that I did not refer to the interface and used directly QgsLegendInterface.addGroup – malagueff Jul 16 '13 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. – malagueff Jul 17 '13 at 05:35
  • @malagueff, Please edit your question per your comment. – artwork21 Apr 02 '14 at 14:36