Let's assume there is a polygon layer called 'test2' with its attribute table, see the image below.
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.
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:
add the source fields to the centroids layer (
addition 1
)The
QgsVectorLayer
class contains thefields()
andupdateFields()
methods.The
QgsVectorDataProvider
class has theaddAttributes()
method.copy the source feature attributes to the new feature (
addition 2
)The
QgsFeature
class possesses thesetAttributes()
method.Here the complete working code :
The code above will result into:
References: