25
25
26
26
__revision__ = '$Format:%H$'
27
27
28
+ import uuid
29
+
28
30
from PyQt4 .QtCore import *
29
31
from qgis .core import *
30
32
from processing .core .ProcessingConfig import ProcessingConfig
@@ -274,3 +276,65 @@ def combineVectorFields(layerA, layerB):
274
276
fields .append (field )
275
277
276
278
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