Sunday, 20 October 2019

python - Developing QGIS Action which loads a raster


I'm using the action code of this question: "How to create a QGIS Action which loads a raster?"


qgis.utils.iface.addRasterLayer('E:\\Plot Sheet Devt\\1974-1984\\1250k\\[% Grid_Ref %].TIF', '[% Grid_Ref %]')

It is very useful for my work and I would need some more functions. The first one is that the action layer remains selected after the action. Now after loading raster It doesn't remain selected. I tried to add this code:


vl = QgsMapLayerRegistry.instance().mapLayersByName('catalogo_CTR')
iface.setActiveLayer(vl)

but It doesn't work.


Other functions could be:




  • to automatically assign SRC to loaded rasters

  • to create a group of layer where to load the raster.



Answer



Try using the following code in your Action Text which should do the following:



  • Keeps your 'catalogo_CTR' layer as active

  • Creates a new group to contain the raster layers if one does not exist

  • Sets the crs for any loaded raster


  • Adds the raster layer to the group with the crs applied


Here is the code:


from PyQt4.QtCore import QFileInfo
vl = QgsMapLayerRegistry.instance().mapLayersByName('catalogo_CTR')[0]
qgis.utils.iface.setActiveLayer(vl)
root = QgsProject.instance().layerTreeRoot()
group_name = "Raster layers"
group = root.findGroup(group_name)
if group == None:

group = root.addGroup("Raster layers")
else:
pass
fileName = 'E:/Plot Sheet Devt/1974-1984/1250k.tif'
fileInfo = QFileInfo(fileName)
baseName = '[% Grid_Ref %]'
rlayer = QgsRasterLayer(fileName, baseName)
crs = QgsCoordinateReferenceSystem()
crs.createFromSrid(27700)
rlayer.setCrs(crs)

QgsMapLayerRegistry.instance().addMapLayer(rlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(rlayer))

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