5

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?

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.