[GIS] How to remove memory layer from memory

memorypyqgisqgis

I have a plugin that creates a memory layer and displays it on the canvas. If I run the plugin a second time after removing the memory layer from the layer list panel without closing QGIS the memory layer is produced along with the previously created layer. It seems as though the memory layer name cannot be reused until QGIS is closed. Is there a way to clear this layer from the memory to rerun the plugin?

###Create new layer
vecLineURI = "LineString?crs=epsg:4326&field=id:integer"
vecLine = QgsVectorLayer(vecLineURI,"point2line","memory")
pr = vecLine.dataProvider()

###Start editing
vecLine.startEditing()

###Add Feature
feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromWkt(lneWKT))
feat.setAttributes([1])
pr.addFeatures( [feat] )

####Update Extents
vecLine.updateExtents()

###Commit Changes
vecLine.commitChanges()

###Load layer
QgsMapLayerRegistry.instance().addMapLayer(vecLine)

I was removing the layer at the start of the plugin open…

layerMap = QgsMapLayerRegistry.instance().mapLayers()
for name, layer in layerMap.iteritems():
    if "point2line" in name:
        QgsMapLayerRegistry.instance().removeMapLayer(layer)

…but this only removed items from the layer panel not from memory.

Best Answer

To remove the memory layer from QGIS and from memory use:

QgsMapLayerRegistry.instance().removeMapLayer(myMemoryLayer.id())

If you are working with memory layers outside of QGIS and you want to remove it from memory you will have to add it then remove it like:

QgsMapLayerRegistry.instance().addMapLayer(myMemoryLayer)
QgsMapLayerRegistry.instance().removeMapLayer(myMemoryLayer.id())