2

I know that it is possible to apply default fill/line/point and colour ramp styles for layers within a project, However...

I have a model which spits out raster layers with defined names (e.g. NAME_XXXX_wd). I don't want to apply a colour ramp but instead an actual style file. Is it possible to set up a project that would automatically apply a style file to an added raster layer based on the name and how might you do it?

I'd also be happy to select the layer in the TOC and hit a toolbar button but would prefer something completely automatic.

1

Might not be fully automatic but you could run a function in your Python Console which loads a style file from a specified folder with the same name as your raster. Insert the following code into the console:

def run(name):
    # Change path accordingly
    style_path = 'C:/Users/You/Desktop/Style_Folder/' + name + '.qml'
    for layer in QgsMapLayerRegistry.instance().mapLayers().values():
        if layer.type() == QgsMapLayer.RasterLayer:
            if name in layer.name():
                layer.loadNamedStyle(style_path)
                layer.triggerRepaint()
                qgis.utils.iface.legendInterface().refreshLayerSymbology(layer)

Now when you want to add a style file to a raster called "NAME-XXXX", type the following in the console (note the single quotation marks):

run('NAME')

This searches for a style file called "NAME" and if any layer includes the word "NAME" in their actual name, then the style file will be applied.

  • 1
    Tip: You can do QgsMapLayerRegistry.instance().mapLayersByName() to just get the layers with the matching name without the loop. – Nathan W Jun 22 '16 at 10:55
  • Ooh that is tantalisingly close. Is it capable of doing wildcards? For example my rasters are called NAME-XXXX where the XXXX is an iterating number so could it be set up to search just for a name stub? – Ed Rollason Jun 22 '16 at 10:56
  • @NathanW - Pro tip from a pro! Will try and implement that into the script ;) – Joseph Jun 22 '16 at 11:37
  • @EdRollason - Made a slight edit to the code which should now check to see if the style name is used in the layer name =) – Joseph Jun 22 '16 at 11:39
  • 1
    That works well thanks - I'll leave it open for 24hr to see if anyone suggests anything else and then I'll mark it answered. Now i should look at implementing it as a plugin I guess! – Ed Rollason Jun 22 '16 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.