1

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 layer.name() after it hase been removed from layers panel, I get an error message.

Edit:

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

2
  • Would you know the layer id?
    – Joseph
    Commented Oct 11, 2018 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 Commented Oct 11, 2018 at 12:57

2 Answers 2

1

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():
    print layer.name()
1
  • It is when the layer is no longer in the panel i get some problems, and the layers will have many different names. Commented Oct 11, 2018 at 12:59
1

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


my_layers=[]

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

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

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

QgsMapLayerRegistry.instance().layerRemoved.connect(layerRemoved)

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