Skip to content

Commit 71e57a7

Browse files
ptormenealexbruy
authored andcommittedMar 25, 2014
New method to duplicate a vector layer in memory and optionally add it to the map registry
1 parent e26b6b5 commit 71e57a7

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
 

‎python/plugins/processing/tools/vector.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525

2626
__revision__ = '$Format:%H$'
2727

28+
import uuid
29+
2830
from PyQt4.QtCore import *
2931
from qgis.core import *
3032
from processing.core.ProcessingConfig import ProcessingConfig
@@ -274,3 +276,65 @@ def combineVectorFields(layerA, layerB):
274276
fields.append(field)
275277

276278
return fields
279+
280+
281+
def duplicate_in_memory(layer, new_name='', add_to_registry=False):
282+
"""
283+
Return a memory copy of a layer
284+
285+
:param layer: QgsVectorLayer that shall be copied to memory.
286+
:type layer: QgsVectorLayer
287+
288+
:param new_name: The name of the copied layer.
289+
:type new_name: str
290+
291+
:param add_to_registry: if True, the new layer will be added to
292+
the QgsMapRegistry
293+
:type: bool
294+
295+
:returns: An in-memory copy of a layer.
296+
:rtype: QgsMapLayer
297+
298+
"""
299+
if new_name is '':
300+
new_name = layer.name() + ' TMP'
301+
302+
if layer.type() == QgsMapLayer.VectorLayer:
303+
v_type = layer.geometryType()
304+
if v_type == QGis.Point:
305+
type_str = 'Point'
306+
elif v_type == QGis.Line:
307+
type_str = 'Line'
308+
elif v_type == QGis.Polygon:
309+
type_str = 'Polygon'
310+
else:
311+
raise RuntimeError('Layer is whether Point nor '
312+
'Line nor Polygon')
313+
else:
314+
raise RuntimeError('Layer is not a VectorLayer')
315+
316+
crs = layer.crs().authid().lower()
317+
my_uuid = str(uuid.uuid4())
318+
uri = '%s?crs=%s&index=yes&uuid=%s' % (type_str, crs, my_uuid)
319+
mem_layer = QgsVectorLayer(uri, new_name, 'memory')
320+
mem_provider = mem_layer.dataProvider()
321+
322+
provider = layer.dataProvider()
323+
v_fields = provider.fields()
324+
325+
fields = []
326+
for i in v_fields:
327+
fields.append(i)
328+
329+
mem_provider.addAttributes(fields)
330+
331+
for ft in provider.getFeatures():
332+
mem_provider.addFeatures([ft])
333+
334+
if add_to_registry:
335+
if mem_layer.isValid():
336+
QgsMapLayerRegistry.instance().addMapLayer(mem_layer)
337+
else:
338+
raise RuntimeError('Layer invalid')
339+
340+
return mem_layer

0 commit comments

Comments
 (0)
Please sign in to comment.