PyQGIS Attribute Inheritance – Creating New Layer with All Attributes Inherited from Original Layer Using PyQGIS

fields-attributesgeometry-conversionpyqgisvector-layer

Let's assume there is a polygon layer called 'test2' with its attribute table, see the image below.

input

With the code below I am creating a new layer as centroids of original features

layer = iface.activeLayer()

vl = QgsVectorLayer("Point?crs={}&index=yes".format(layer.crs().authid()), "centroids", "memory")
provider = vl.dataProvider()

for feat in layer.getFeatures():
    new_geom = feat.geometry().centroid()
    new_feat = QgsFeature()
    new_feat.setGeometry(new_geom)
    provider.addFeature(new_feat)
    
QgsProject.instance().addMapLayer(vl)

and I achieve what I intended to, see the image below, but only in terms of geometries.

result

My question is: how to get all the attributes ("id", "X_East", and "Y_North") from the original layer and bring them into a new layer?

I have seen this thread: Creating QgsFeature with default attributes using PyQGIS, but it did not work:

for feat in layer.getFeatures():
    new_feat = QgsVectorLayerUtils.createFeature(layer)
    new_geom = feat.geometry().centroid()
    new_feat.setGeometry(new_geom)
    provider.addFeature(new_feat)

Moreover, I do not understand how to transfer all attributes at once, not just one by one.

I am aware of the "native:centroids", which can simplify my work, however, I want to achieve the desired output without application of any geoalgorithm.


References:

Best Answer

I reviewed your code and added just a few lines:

  1. add the source fields to the centroids layer (addition 1)

    The QgsVectorLayer class contains the fields() and updateFields() methods.

    The QgsVectorDataProvider class has the addAttributes() method.

  2. copy the source feature attributes to the new feature (addition 2)

    The QgsFeature class possesses the setAttributes() method.

Here the complete working code :

layer = iface.activeLayer()

vl = QgsVectorLayer("Point?crs={}&index=yes".format(layer.crs().authid()), "centroids", "memory")
provider = vl.dataProvider()

### addition 1
provider.addAttributes(layer.fields())
vl.updateFields()
###

for feat in layer.getFeatures():
    new_geom = feat.geometry().centroid()
    new_feat = QgsFeature()
    new_feat.setGeometry(new_geom)
    ### addition 2
    new_feat.setAttributes(feat.attributes())
    ###
    provider.addFeature(new_feat)

QgsProject.instance().addMapLayer(vl)

The code above will result into:

result


References: