8

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

17

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.

|improve this answer|||||
  • I cannot find explanation to what ToC means? – J.A.Cado Dec 7 '17 at 8:42
  • 1
    Layer tree, legend, ToC, they are names normally used in GIS when refering to the list of layers and groups in a software. – Germán Carrillo Dec 7 '17 at 13:51
4

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

Example:

iface.legendInterface().addGroup( 'abc')
|improve this answer|||||
  • 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 5:35
  • @malagueff, Please edit your question per your comment. – artwork21 Apr 2 '14 at 14:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.