5

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:

asked Apr 16, 2022 at 13:32

1 Answer 1

6

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:

Taras
35.7k5 gold badges77 silver badges151 bronze badges
answered Apr 16, 2022 at 13:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.