Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 );
share|improve this question

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:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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