I'm tring to programmatically create layer sequence also using groups. Simple python code:

layer = QgsVectorLayer("004cp000.shp", "004cp000", "ogr")
legend = qgis.utils.iface.legendInterface()
index = legend.addGroup ("G1")
index = legend.addGroup ("G2",index)
legend.moveLayer (legend.layers()[0],index)
  • How it is possible to remove a nested group ? qgis.utils.iface.legendInterface().removeGroup only works with top level groups.

  • How a layer can be moved into a nested group? qgis.utils.iface.legendInterface().moveLayer only works with top level groups.

  • How can I move a layer before or after a another layer inside the same group?

After some research into QGis Source code I've discovered that it is not possible to move a layer into a sub group and also it is not possible to delete a soub group.

void QgsLegend::moveLayer( QgsMapLayer *ml, int groupIndex )
  if ( !ml )

  QgsLegendLayer *layer = findLegendLayer( ml->id() );
  if ( !layer )

  QgsLegendGroup *group = dynamic_cast<QgsLegendGroup*>( topLevelItem( groupIndex ) );
  if ( !group )

  insertItem( layer, group );

  emit itemMovedGroup( dynamic_cast<QgsLegendItem*>( layer ), groupIndex );

void QgsLegend::removeGroup( int groupIndex )
  QgsLegendGroup * lg = dynamic_cast<QgsLegendGroup *>( topLevelItem( groupIndex ) );
  if ( lg )
    removeGroup( lg );

You should really update QGIS to v.>=2.4. Martin Dobias refactored the QGIS layer list widget (aka legend or ToC), enabling developers to manipulate legend objects from the QGIS API.

Martin has recently posted a couple of articles on how to use the new legend API from Python:

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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