Skip to content
Permalink
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 71e57a7a2570a0cfac9aaeae61897083075d6932
Showing with 64 additions and 0 deletions.
  1. +64 −0 python/plugins/processing/tools/vector.py
@@ -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):
fields.append(field)

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 = layer.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'
else:
raise RuntimeError('Layer is whether Point nor '
'Line nor Polygon')
else:
raise RuntimeError('Layer is not a VectorLayer')

crs = layer.crs().authid().lower()
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:
fields.append(i)

mem_provider.addAttributes(fields)

for ft in provider.getFeatures():
mem_provider.addFeatures([ft])

if add_to_registry:
if mem_layer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(mem_layer)
else:
raise RuntimeError('Layer invalid')

return mem_layer

0 comments on commit 71e57a7

Please sign in to comment.
You can’t perform that action at this time.