2

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()

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

#polygon2
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:
                selected_feats.append(feat2)

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

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

mem_layer = QgsVectorLayer(uri,
                           "mem_layer",
                           "memory")

for i, feat in enumerate(selected_feats):
    feat.setAttributes(selected_feats[i].attributes())

prov = mem_layer.dataProvider()
attr = layers[1].dataProvider().fields().toList()
prov.addAttributes(attr)
mem_layer.updateFields()
prov.addFeatures(selected_feats)

QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

1 Answer 1

1

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()
prov.addAttributes(attr)
mem_layer.updateFields()
prov.addFeatures(selected_feats)
2
  • 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
    Commented Jun 27, 2018 at 13:19
  • Use something like feat2.setAttributes(feat1.attributes())
    – strythe
    Commented Apr 17, 2019 at 1:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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