5

I have a large number of raster model files of water depths with corresponding velocity vectors in point shapefiles. I want to be able to 'walk through' the results displaying the depths and velocity vectors on top of each other but without having to select both layers in the TOC.

Would it be possible to write python code that would turn on the corresponding vector layer when a raster was turned on in the TOC, based on matching its name?

It would ideally need no user input except to run the code before the user started to visualise the results.

The two files (one raster and one shapefile) have essentially the same names identifying the model name and containing a numeric identifier which would be unique to just those two layers.

  • 1
    Could you create a number of Groups in the legend, each with a raster and vector layer, and then you just need to turn on/off the visibility of the Group, and it will control the visibility of the two layers in it? – Spacedman Jan 16 '17 at 14:25
  • Unfortunately I'm talking 200+ rasters – Ed Rollason Jan 16 '17 at 20:52
  • No I don't want all other layers turned off, just to turn on a name-matched vector layer - I think Joseph has the makings of it in the answer below but need to check it works. – Ed Rollason Jan 17 '17 at 15:25
4

Try running the following code in the Python Console. Essentially when you toggle the visibility of a raster layer, it finds a vector layer with the same name and its visibility is also toggled. The code is only applied to raster layers so if a vector layer has a matching name with a raster layer, its visibility cannot be toggled (i.e. you can only view it by clicking on its associated raster).

from PyQt4.QtCore import *
def match_layers():
    for rLayer in QgsMapLayerRegistry.instance().mapLayers().values():
        if rLayer.type() == QgsMapLayer.RasterLayer:
            name = rLayer.name()
            node = root.findLayer(rLayer.id()) 
            if node.isVisible() == Qt.Checked: 
                for vLayer in QgsMapLayerRegistry.instance().mapLayers().values():
                    if rLayer.name() == vLayer.name():
                        iface.legendInterface().setLayerVisible(vLayer, True)
                    else:
                        pass
            else:
                for vLayer in QgsMapLayerRegistry.instance().mapLayers().values():
                    if rLayer.name() == vLayer.name():
                        iface.legendInterface().setLayerVisible(vLayer, False)
        else:
            pass

root = QgsProject.instance().layerTreeRoot()
root.visibilityChanged.connect(match_layers)

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.