1

In QGIS 3.4, I would like to automatize and uniformize the appearance of each layer.

I would like that each new layer is created:

  • with the alpha slider activated

Alpha Slider

  • with Feature count activated

Layer Entity Count

1

You could use something like the following in the Python Console which:

  • Enables the feature count setting for vector-type layers
  • Enables the transparency slider for any layer

These are applied whenever a layer is added:

def enableFeatCountAndAlphaSlider(layers):
    root = QgsProject.instance().layerTreeRoot()
    layer = layers[0]
    # Enable feature count for vector-type layers
    if layer.type() == QgsMapLayer.VectorLayer:
        myLayerNode = root.findLayer(layer.id())
        myLayerNode.setCustomProperty("showFeatureCount", True)
    # Enable transparency slider
    if layer.customProperty("embeddedWidgets/count") != 1 or layer.customProperty("embeddedWidgets/0/id") != u'transparency':
        layer.setCustomProperty("embeddedWidgets/count", 1)
        layer.setCustomProperty("embeddedWidgets/0/id", "transparency")
    # Refresh legend symbology
    iface.layerTreeView().refreshLayerSymbology(layer.id())

# Connect "legendLayersAdded" event to "enableFeatCountAndAlphaSlider" function
QgsProject.instance().legendLayersAdded.connect(enableFeatCountAndAlphaSlider)

To disconnect the function, use:

QgsProject.instance().legendLayersAdded.disconnect(enableFeatCountAndAlphaSlider)

enableFeatCountAndAlphaSlider

  • 1
    Works directly for me. Thanks a lot for your detailed answer ! I am just beginning with pyScript, it helped a lot. – kFly Jul 26 at 17:04
  • What do you use to create the animated picture you add in your answer ? – kFly Jul 26 at 17:07
  • 1
    @kFly - Most welcome! Glad it helped :). I used ScreenToGif. – Joseph Jul 30 at 9:52
  • 1
    @kFly - You don't run the function manually, you connect it to a signal which is emitted whenever a layer is added to QGIS which is what this line does: QgsProject.instance().legendLayersAdded.connect(enableFeatCountAndAlphaSlider) – Joseph Aug 1 at 14:59
  • 1
    @kFly - I tested the script as a startup. I had to include the lines from qgis.core import QgsMapLayer, QgsProject and from qgis.utils import iface at the beginning. After QGIS has loaded, it works. Did you put it in the same directory called "Python" or did you put it inside this directory? I'm not a linux user so not sure if this is the correct path or not. If it is correct then perhaps the issue lies elsewhere. – Joseph Aug 2 at 9:10

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.