Developing QGIS Action which loads a raster

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