[QGIS-Developer] Event to register adding layers in QGIS

Richard Duivenvoorde rdmailings at duif.net
Fri Aug 26 02:17:34 PDT 2022


I have a plugin which fires after a layer is added (fired both via drag/drop and when loading project)

would these be usable?

QgsProject.instance().layerWasAdded.connect(XXX) # after

QgsProject.instance().legendLayersAdded.connect(XXX) # before

see https://qgis.org/pyqgis/master/core/QgsProject.html?highlight=legendlayersadded#qgis.core.QgsProject.legendLayersAdded

Regards,

Richard Duivenvoorde

On 8/26/22 11:01, Bo Victor Thomsen via QGIS-Developer wrote:
> Hi list -
> 
> I have a small "startup.py" project - The goal is to register every time a user opens af layer in QGIS in a organization with lots of QGIS users. The end goal is to find data sources that are maintained but actually not used.
> 
> To that purpose I created the following script as a "proof of concept":
> 
> *from qgis.core import QgsProject, QgsMessageLog, Qgis, QgsLayerTreeLayer
> from datetime import datetime
> import os
> 
> 
> def onAddedChildren(node, indexFrom, indexTo):
> 
>      for i in range(indexFrom, indexTo+1):
>          child = node.children()[i]
>          if isinstance(child, QgsLayerTreeLayer):
>              layer = child.layer()
>              name = ''
>              uri = ''
>              if (layer):
>                  name = layer.name()
>                  datap = layer.dataProvider()
>                  if datap:
>                      uri = datap.dataSourceUri()
>              strx = '"{}";"{}";"{}";"{}";"{}"'.format(datetime.today().strftime('%Y-%m-%d %H:%M:%S'),os.getlogin(),child.name(),name,uri)
>              with open("d:/tmp/loglag.csv", "a") as g:
>                  g.write(strx+'\n')
> 
> root = QgsProject.instance().layerTreeRoot()
> root.addedChildren.connect(onAddedChildren)
> *
> 
> (I know - I might into trouble with users appending data to the same file at the same time, but that is solveable)
> 
> The above script works like a charm, when a user add a single layer using the data source manager. But it partially fails when opening a project. The layers are registred, but it doesn't register the uri for the individual layers. I assume the event "addedChildren" is fired before the layers is fully loaded.
> 
> So is there some other event I can use to get my full layer info ?
> 
> -- 
> 
> Med venlig hilsen / Kind regards
> 
> Bo Victor Thomsen
> 
> 
> _______________________________________________
> QGIS-Developer mailing list
> QGIS-Developer at lists.osgeo.org
> List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer
> Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer



More information about the QGIS-Developer mailing list