Skip to content
Browse files
New method to duplicate a vector layer in memory and optionally add i…
…t to the map registry
  • Loading branch information
ptormene authored and alexbruy committed Mar 25, 2014
1 parent e26b6b5 commit 71e57a7
Showing 1 changed file with 64 additions and 0 deletions.
@@ -25,6 +25,8 @@

__revision__ = '$Format:%H$'

import uuid

from PyQt4.QtCore import *
from qgis.core import *
from processing.core.ProcessingConfig import ProcessingConfig
@@ -274,3 +276,65 @@ def combineVectorFields(layerA, layerB):

return fields

def duplicate_in_memory(layer, new_name='', add_to_registry=False):
Return a memory copy of a layer
:param layer: QgsVectorLayer that shall be copied to memory.
:type layer: QgsVectorLayer
:param new_name: The name of the copied layer.
:type new_name: str
:param add_to_registry: if True, the new layer will be added to
the QgsMapRegistry
:type: bool
:returns: An in-memory copy of a layer.
:rtype: QgsMapLayer
if new_name is '':
new_name = + ' TMP'

if layer.type() == QgsMapLayer.VectorLayer:
v_type = layer.geometryType()
if v_type == QGis.Point:
type_str = 'Point'
elif v_type == QGis.Line:
type_str = 'Line'
elif v_type == QGis.Polygon:
type_str = 'Polygon'
raise RuntimeError('Layer is whether Point nor '
'Line nor Polygon')
raise RuntimeError('Layer is not a VectorLayer')

crs =
my_uuid = str(uuid.uuid4())
uri = '%s?crs=%s&index=yes&uuid=%s' % (type_str, crs, my_uuid)
mem_layer = QgsVectorLayer(uri, new_name, 'memory')
mem_provider = mem_layer.dataProvider()

provider = layer.dataProvider()
v_fields = provider.fields()

fields = []
for i in v_fields:


for ft in provider.getFeatures():

if add_to_registry:
if mem_layer.isValid():
raise RuntimeError('Layer invalid')

return mem_layer

0 comments on commit 71e57a7

Please sign in to comment.