TransWikia.com

How to remove memory layer from memory?

Geographic Information Systems Asked by anon1234 on December 1, 2020

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.

2 Answers

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())

Answered by artwork21 on December 1, 2020

QgsMapLayerRegistry has been depreciated as of QGIS 3 as per this answer

QGIS API Documentation

The way to do this using QGIS 3.# is as follows:

First add the in memory layer to the project

QgsProject.instance().addMapLayer(myMemoryLayer)

Then remove the map layer from the project

QgsProject.instance().removeMapLayer(myMemoryLayer.id())

Answered by kingurr on December 1, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP