1

I am writing a Python method which I want the mouse click event to connect to. The method selects objects from layers that satisfy certain conditions. I want to select from any visible layer, that has features in the current map extent.

To evaluate which layer is visible I check the property:

QgsProject.instance().layerTreeRoot().findLayer(layer.id()).isVisible()

There are some layers with scale dependent visibility. I don't want to select objects from layers, that are not visible due to the current map scale.

isVisible() from the line of code above returns True, even if the layer is not visible due to the current scale, but is checked in the legend tree.

My question: is there another way to check if a layer with scale based visibility is out of the visible scale interval, then comparing the map scale with minimumScale() and maximumScale() of each layer?

3

You could use the iface.mapCanvas().layers() method, which gives you only the checked layers in the ToC, i.e., no need to iterate through all map layers.

You should then iterate through checked layers to evaluate if their scale-based visibility contains the current map scale, like this:

canvas = iface.mapCanvas()
for layer in canvas.layers():
    if layer.hasScaleBasedVisibility():
        if layer.maximumScale() > canvas.scale() and layer.minimumScale() < canvas.scale():
            print "Layer",layer.name(),"is visible!"
    else:
            print "Layer",layer.name(),"is visible!"

I'm not aware of another PyQGIS method to do that.

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.