Is there an easy way to check if a layer created in pyqgis and addet to layers panel have been removed? I tried to use the layers = QgsProject.instance().mapLayersByName('my layer name'), but I don't nessesarely know the layer name, and if I use after it hase been removed from layers panel, I get an error message.


Error message: RuntimeError: wrapped C/C++ object of type QgsVectorLayer has been deleted

This message comes when i try to use any of the layer objects functions, but the layer is stil registerd as a QgsVectorLayer

This is for QGIS 2.18

  • Would you know the layer id? – Joseph Oct 11 at 11:35
  • I suppose i could save the id or the name separately, but I can't use the layer function to get the id – Kasper Skjeggestad Oct 11 at 12:57

I'm not sure how to check for a layer which you do not know the name but this option will at least list all layer names in the layer panel:

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
  • It is when the layer is no longer in the panel i get some problems, and the layers will have many different names. – Kasper Skjeggestad Oct 11 at 12:59

You could save the ID's of your generated layers and connect to the layerremoved signal to check if the removed layer is one of your generated layers.

Something to test in your python console:

from qgis.PyQt.QtCore import ( QObject)
from qgis.core import QGis, QgsVectorLayer, QgsMapLayerRegistry


def createTmpLyr():
    uri = "Point?crs=epsg:4326&field=id:integer&field=Pt:string(20)&index=yes"
    memlayer = QgsVectorLayer(uri, "temporary_points", "memory")
    print my_layers

#create 4 testlayer
for x in range(0, 4):

def layerRemoved(layer):
    if layer in my_layers:
        print "Layer "+layer+" removed"


Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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