I have a layer where only the first row in the attribute table has a geometry. I want to copy this geometry to all other rows of the attribute table of this layer but the geometry is still empty.

layer = iface.activeLayer()

# Get the first feature from the layer
feature = layer.getFeatures()
n = next(feature)

# save geometry in variable
geom = n.geometry()
# add geometry to all rows of attribute table
for f in layer.getFeatures():

# print geometry of all rows of attribute table
for g in layer.getFeatures():
    print (g.geometry())

  • output of print geometry is: <QgsGeometry: MultiLineString ((390348.37778519437415525 5814565.59899287391453981, 390355.81410851434338838 5815164.22302012797445059))> <QgsGeometry: null> <QgsGeometry: null>
    – Robert B K
    Feb 3 at 16:36

1 Answer 1


Try this. Backup first, it will modify the layer in place.

layer = QgsProject.instance().mapLayersByName("thelayer")[0]
pr = layer.dataProvider()

#Fetch the geometry of the first feature
featureiterator = layer.getFeatures()
first_feature = next(featureiterator)
first_geometry = first_feature.geometry()

geometryMap = {} #A dict to store each features id and new geometry

for f in featureiterator: #The first feature is already fetched, so this will continue iterating at the second feature
    geometryMap[f.id()] = first_geometry #For each feature, store its id and the first features geometry in geometryMap dict.

pr.changeGeometryValues(geometryMap) #Apply the geometry map

enter image description here

  • 1
    Thank you so much, it works!!
    – Robert B K
    Feb 5 at 14:32

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.