7

The following code inserts my new_layer just above the active layer in the QGIS ToC.

new_layer = iface.addRasterLayer(...) 

Instead, I'd like my new_layer to be inserted at the top of the QGIS ToC.

Do you know how can I do it?

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
Eric H.
  • 243
  • 2
  • 8
  • did you check http://gis.stackexchange.com/questions/41977/sort-layers-in-qgis-table-of-contents? – underdark Feb 18 '14 at 19:48
  • 2
    Is it necessary to create groups to move up a layer ? I thought of something like: li = iface.legendInterface(); li.moveLayerIndex(new_layer, 0), just as simple as manuallly dragging up a layer in the left column to put it in first rank. Does a similar method exist ? – Eric H. Feb 19 '14 at 06:23

2 Answers2

8

By using the new Layer tree (aka legend or ToC) added by Martin Dobias since QGIS v.2.4, you can load a layer to the top of the ToC following these steps:

  1. Get a reference of the layer tree

    root = QgsProject.instance().layerTreeRoot()
    
  2. Create the layer object

    from PyQt4.QtCore import QFileInfo
    fileName = "/path/to/raster/file.tif"
    fileInfo = QFileInfo(fileName)
    baseName = fileInfo.baseName()
    mylayer = QgsRasterLayer(fileName, baseName)
    
  3. Add the layer to the QGIS Map Layer Registry

    QgsMapLayerRegistry.instance().addMapLayer(mylayer, False)
    
  4. Insert the layer at the top of the ToC (position 0)

    root.insertLayer(0, mylayer)
    

That's it!

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
0

I have not found a way to do it after having added the layers but two alternative options are:

  • Create groups, then you can use moveLayers to put layers in a group
  • Add the layers in the right order !
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Yves
  • 57
  • 1
  • 3