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?


1 Answer 1


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.

  • Would you mind expanding on your last point with attributes not at the correct field? I get this problem but don't understand your recommendation
    – Leo
    Commented Jul 29, 2020 at 23:45
  • Well, my problem was around the fields being set and the layer.dataProvider() order. The no only have to be the same ones, but declared in the right order
    – Leo
    Commented Jul 30, 2020 at 1:19

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