Tuesday 14 May 2019

Running PyQGIS script when opening any project in QGIS?


This question is a follow-up of this topic: Setting Alpha Slider and Feature Count ON by default using QGIS?


I am trying to run this script for each new project I open.


But I am failing of making it active.


From my knowledge of QGIS, a script called startup.py should be created.


In QGIS 3, this script is there



[Linux] /$HOME/.local/share/QGIS/QGIS3/profiles/default/python


[Windows] C:\Users\You\AppData\Roaming\QGIS\QGIS3\profiles\default\python\startup.py


(You can check this directory under : Settings > User Profile > Open Active Profile Directory)


My startup.py script is :


from qgis.core import QgsMapLayer
from qgis.core import QgsProject
from qgis.utils import iface
import enableFeatCountAndAlphaSlider #Activation sub

QgsProject.instance().legendLayersAdded.connect(enableFeatCountAndAlphaSlider)


The routine enableFeatCountAndAlphaSlider is stored in the same directory as startup.py and as the following content:


def enableFeatCountAndAlphaSlider(layers):
# By Joseph (https://gis.stackexchange.com/questions/329919/qgis-3-4-setting-alpha-slider-and-feature-count-on-by-default/329984#329984)
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)


I have got no message from qgis windows. When running manually startup.py from the console I have got the following error message:



QgsProject.instance().legendLayersAdded.connect(enableFeatCountAndAlphaSlider) NameError: name 'QgsProject' is not defined



What am I missing and how do I correct it?




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...