Showing with 50 additions and 0 deletions.
  1. +50 −0 python/plugins/processing/tools/vector.py
50 changes: 50 additions & 0 deletions python/plugins/processing/tools/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

__revision__ = '$Format:%H$'

import uuid

from PyQt4.QtCore import *
from qgis.core import *
from processing.core.ProcessingConfig import ProcessingConfig
Expand Down Expand Up @@ -274,3 +276,51 @@ def combineVectorFields(layerA, layerB):
fields.append(field)

return fields


def duplicateInMemory(layer, newName='', addToRegistry=False):
"""Return a memory copy of a layer
layer: QgsVectorLayer that shall be copied to memory.
new_name: The name of the copied layer.
add_to_registry: if True, the new layer will be added to the QgsMapRegistry
Returns an in-memory copy of a layer.
"""
if newName is '':
newName = layer.name() + ' (Memory)'

if layer.type() == QgsMapLayer.VectorLayer:
geomType = layer.geometryType()
if geomType == QGis.Point:
strType = 'Point'
elif geomType == QGis.Line:
strType = 'Line'
elif geomType == QGis.Polygon:
strType = '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()
myUuid = str(uuid.uuid4())
uri = '%s?crs=%s&index=yes&uuid=%s' % (strType, crs, myUuid)
memLayer = QgsVectorLayer(uri, newName, 'memory')
memProvider = memLayer.dataProvider()

provider = layer.dataProvider()
fields = provider.fields().toList()
memProvider.addAttributes(fields)
memLayer.updateFields()

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

if addToRegistry:
if memLayer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(memLayer)
else:
raise RuntimeError('Layer invalid')

return memLayer