[GIS] How to move a layer in QGIS Toc above an existing group

pyqgisqgistable of contents

If in QGIS TOC a group already exists and I add a new layer via

QgsVectorLayer* lyr= mQGisIface->addVectorLayer(uri->uri(),Title, myProviderName);

the new layer will be inserted within the group. How can I move it outside/above the group?

Best Answer

You can do that by following these steps (QGIS >= v.2.4):

  1. Get the layer tree object

    root = QgsProject.instance().layerTreeRoot()
    
  2. Find the desired group by name

    mygroup = root.findGroup("group1")
    
  3. Get the group index

    parentGroup = mygroup.parent()
    groupIndex=-1
    for child in parentGroup.children():
         groupIndex+=1
         if mygroup == child:
             break
    
  4. Create the new layer object

    mylayer = QgsVectorLayer("/PathToYour/data.shp", "my layer", "ogr")
    
  5. Add the layer to the QGIS Map Layer Registry

    QgsMapLayerRegistry.instance().addMapLayer(mylayer, False)
    
  6. Insert the layer above the group

    parentGroup.insertChildNode(groupIndex, QgsLayerTreeLayer(mylayer))