I have a plugin with my own map canvas and I create a button in order to remove all the layers visible or opened in map canvas. I use this lines:


And it works but I noted that the layers are not in canvas but exist even that, I think they are in memory. How can I permanently remove the layers?

  • How are you suspecting they are still in memory, can you expand more about this?
    – artwork21
    Oct 21, 2015 at 11:43
  • The layers are removed of visual field, but when I use self.canvas.layerCount() to count the number of layers in canvas, they still give me the number of layers that I removed. Oct 21, 2015 at 11:45
  • They are perhaps still stored within the layer registry. This post might help in purging the removed layers: Is there a purge function to remove layers from a qgs file which are not present in the Layers pane?
    – Joseph
    Oct 21, 2015 at 11:48
  • When I add a layer using QgsMapLayerRegistry.instance().addMapLayer(layerName) method and remove it using QgsMapLayerRegistry.instance().removeAllMapLayers() I get a count of 0. How are you adding your layers? Is the returned count for all the layers that were there before or just one or two?
    – artwork21
    Oct 21, 2015 at 12:01
  • Yes I am using QgsMapLayerRegistry.instance().addMapLayer(rlayer) and then self.canvas.setExtent(rlayer.extent()) but when I try to remove, it removes the map but the count is never 0. The count is the number of layers that were added. Oct 21, 2015 at 12:24

1 Answer 1


I found a solution. I could not to change the result obtained by self.canvas.layerCount() but if I use QgsMapLayerRegistry.instance().count() I get 0 if the layers are removed. So it is what I need.

Thanks for the help.

  • You've asked quite a lot of questions but barely accepted any. Did none of the answers helped? You can atleast accept your own answers.
    – user35594
    Mar 5, 2016 at 20:45

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.