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

closed as off-topic by PolyGeo Jan 22 at 22:06

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "When seeking help to debug/write/improve code always provide the desired behavior, a specific problem/error and the shortest code (as formatted text, not pictures) needed to reproduce it in the question body. Providing a clear problem statement and a code attempt helps others to help you." – PolyGeo
If this question can be reworded to fit the rules in the help center, please edit the question.


For reference, using the new Layer tree (introduced in QGIS v.2.4) 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")

You can even create nested groups (a group into a group):

myGroupA = myGroup1.addGroup("My Group A")

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

  • 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

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


iface.legendInterface().addGroup( 'abc')
  • 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.