I'm new in PyQGIS and wrote a script to read a polygon and get the centroid:
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtCore import *
# insert the location of the shp
layer = iface.addVectorLayer("/media/path/Setor_Censit_Urb_Cast_2010.shp", "Setor", "ogr")
layer2 = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , 'memory')
pts = []
# save the centroid as vector
prov = layer2.dataProvider()
points = []
for feature in layer.getFeatures():
geometry = feature.geometry()
centroid = geometry.centroid().asPoint()
pts = [centroid]
name = feature.attribute("CD_GEOCODI") # select the attribute
# Insert the coordinates in the layer2 shapefile
for x,y in pts:
feat = QgsFeature()
point = QgsPoint(x,y)
feat.setGeometry(QgsGeometry.fromPoint(point))
points.append(feat)
prov.addFeatures(points)
# update extent of the layer
layer2.updateExtents()
# add the layer to the layers panel
QgsMapLayerRegistry.instance().addMapLayers([layer2])
But I want the attributes too. How can I do it?