4

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?

0
6

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.

2
  • 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
    Jul 29 '20 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
    Jul 30 '20 at 1:19

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