[GIS] When does iface.mapCanvas().layers() get updated to the contents of QgsMapLayerRegistry.instance().mapLayers()

layerspyqgisqgis-plugins

Since the topic might be a bit cryptic, I'll try to explain where my problem is.

I am currently developing a QGIS plugin, where I am creating and adding some layers automatically, which I would like to activate afterwards. So far, so good, not a big deal. Hence I am doing this process several times, I created a method for iterating over the layers.

And now the problem is:

I create and add the layer:

type = 'Polygon'
crs = '?crs=' + self.project_crs
shape_layer = QgsVectorLayer(type + crs, layer_name, 'memory')
shape_layer.setProviderEncoding('System')

# add the layer to the layer-legend
QgsMapLayerRegistry.instance().addMapLayer(shape_layer)

But if I want to access the layer by iterating over the iface.mapCanvas().layers() and running:

for layer in self.iface.mapCanvas().layers():

    if layer.name() == layer_name:
        return layer

'None' is returned. Strange thing, because the problem could be avoided, by either accessing the mapCanvas() prior to starting iteration:

layers = self.iface.mapCanvas().layers()
for layer in self.iface.mapCanvas().layers():

    if layer.name() == layer_name:
        return layer

Or, by iterating over either self.iface.legendInterface().layers() or QgsMapLayerRegistry.instance().mapLayers(), which both are "updated" instantly.

Could anyone explain the mechanisms behind the addMapLayer() function and in general regarding the memory management behind QGIS? Or does anyone know where to read something about it?

Best Answer

Generally you access the QgsMapLayerRegistry if you want access to the layer object again. The layer may or may not be in the canvas i.e layers that are not visible are not in canvas.layers().

addMapLayer() should add it to the canvas and update layers() automatically. If not it might be a bug. Like I said it's safer to use the registry to find the layer if you need access to it.