Tuesday 19 June 2018

python - How to add layer/raster with specific position in the QGIS layer list?


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??



Answer



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)




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...