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
# Set destination layer active
iface.setActiveLayer( destinationLayer )
# Turn on editing on destination layer, so we can paste
# Paste features
# 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?


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():
data_provider = destLYR.dataProvider()

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.