4

Using PyQGIS via the QGIS 2.4.0 Python console and the editor, I can create parallel groups for storing some layers with:

MyFirstGroup = iface.legendInterface().addGroup('Group No. 1')
MySecondGroup = iface.legendInterface().addGroup('Group No. 2')

The variables MyFirstGroup and MySecondGroup will store the GroupIDs (apparently 1 & 2). But how can I create the groups in a nested way so that MySecondGroup is a sub-group of MyFirstGroup?

Looking at the API docs, I find the addGroup function twice - one time expecting the parent group with a QTreeWidgetItem and one time via a int parentIndex.

When using the latter form as

MySecondGroup = iface.legendInterface().addGroup('Group No. 2', parentIndex = 1)

then I get a TypeError: QgsLegendInterface.addGroup(QString, bool expand=True, QTreeWidgetItem parent=None): 'parentIndex' is not a valid keyword argument

When only using

MySecondGroup = iface.legendInterface().addGroup('Group No. 2', 1)

or

MySecondGroup = iface.legendInterface().addGroup('Group No. 2', MyFirstGroup)

then groups are not created nested but in parallel.

What is the correct way to achieve this or where do I get the corresponding QTreeWidgetItem object for MyFirstGroup from?

2 Answers 2

4

You may use the addGroup function like this:

MyFirstGroup = iface.legendInterface().addGroup('Group No. 1')
MySecondGroup = iface.legendInterface().addGroup('Group No. 2', true, MyFirstGroup)
2

Legend interface has been refactored since 2.4 version. A detailed description how to add nodes, groups and subgroups can be found here:

http://www.lutraconsulting.co.uk/blog/2014/07/06/qgis-layer-tree-api-part-1/

and here

http://www.lutraconsulting.co.uk/blog/2014/07/25/qgis-layer-tree-api-part-2/

regards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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