I have a criteria to select the features from a layer that overlap the features of another layer, but i do not know how to copy the fields at the same time: Tyhe code does: - two layers (1 and 2) of polygons - if one feature of polygon2 overlap more than 80% one of polygon1, it selects it.

How to also copy the fields of polygon1 to add them to the fields of the selected polygon2?

from qgis.core import *
import processing
import os

mapcanvas = iface.mapCanvas()

layers = mapcanvas.layers()

feats_lyr1 = [ feat for feat in layers[0].getFeatures() ]

feats_lyr2 = [ feat for feat in layers[1].getFeatures() ]

selected_feats = []

for i, feat1 in enumerate(feats_lyr1):
    for j, feat2 in enumerate(feats_lyr2):
        if feat1.geometry().intersects(feat2.geometry()):
            area1 = feat1.geometry().intersection(feat2.geometry()).area()
            area2 = feat2.geometry().area()
            crit =area1/area2
            if crit > 0.8:

epsg = layers[0].crs().postgisSrid()

uri = "Polygon?crs=epsg:" + str(epsg) + "&index=yes"

mem_layer = QgsVectorLayer(uri,

for i, feat in enumerate(selected_feats):

prov = mem_layer.dataProvider()
attr = layers[1].dataProvider().fields().toList()


Just add the source layer fields to a list, use addAttributes(), and updateFields() methods to add the fields:

prov = mem_layer.dataProvider()
attr = layers[0].dataProvider().fields().toList()
  • Thanks for the answer! But how to get the correspondant fields of the other layer, in other word, in the loop, to add the fields of the feat1 to those of feat2?
    – francois
    Jun 27 '18 at 13:19
  • Use something like feat2.setAttributes(feat1.attributes())
    – strythe
    Apr 17 '19 at 1:57

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.