TransWikia.com

Creating QGIS copy-paste features between two layers using PyQGIS?

Geographic Information Systems Asked on March 28, 2021

i want to create a QGIS action which copies features between two points layers using pyqgis .

i have read How to create a QGIS action which copies features between layers? and i try to use this code:

# only QGIS < 2.0
iface = qgis.utils.iface
# Make the source layer active
iface.setActiveLayer( sourceLayer )
# Set the selection on the source layer (Could also be done manually with the selection tools
sourceLayer.setSelectedFeatures( [ 1, 5, 10 ] )
# Copy
iface.actionCopyFeatures().trigger()
# Set destination layer active
iface.setActiveLayer( destinationLayer )
# Turn on editing on destination layer, so we can paste
destinationLayer.startEditing()
# Paste features
iface.actionPasteFeatures().trigger()
# Uncomment to automatically save edits
# destinationLayer.commitChanges()

but in my case i dont need to copy selected features but i need to copy all features from sourceLayer to destinationLayer,and i need to transfer common attributes from sourceLayer to destinationLayer .

What changes do I need in this code?

One Answer

To copy all features; create a list, get features from source layer, create data provider on destination layer, and finally add features to destination layer:

sourceLYR = QgsMapLayerRegistry.instance().mapLayersByName('sourceLayerName')[0]
destLYR = QgsMapLayerRegistry.instance().mapLayersByName('destinationLayerName')[0]
features = []
for feature in sourceLYR.getFeatures():
    features.append(feature)
destLYR.startEditing()
data_provider = destLYR.dataProvider()
data_provider.addFeatures(features)
destLYR.commitChanges()

If the data schemas between the two layers are different this method may not place the attributes under the correct field. If that is the case you'll want to create a feature from the source xy location in the destination layer and then individually map over the attributes.

Answered by artwork21 on March 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP