5

I use addRasterLayer(rast,'Name') but this adds the raster to the top. It is possible to set position when I add raster at once? Is it possible??

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
user7172
  • 1,529
  • 2
  • 24
  • 45

2 Answers2

5

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

  1. Get a reference of the layer tree

    root = QgsProject.instance().layerTreeRoot()

  2. Create the raster 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 (the second argument must be set to False for you to specify a custom position in step 4.)

    QgsMapLayerRegistry.instance().addMapLayer(mylayer, False)

  4. Insert the layer in the third position of the ToC

    root.insertLayer(2, mylayer)

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

I will need to look into that, but you could try to add the layer and than change the order afterwards, if you want to use python anyway. Check out this other thread about changing the order of layers in the TOC for hints.

Mark Verschuur
  • 732
  • 8
  • 22