4

I can't find a solution for auto-refreshing attribute table data.

For instance, how can the data related to features of a Shapefile (e.g., the area) be updated if the feature geometry is changed.

  • No, It won't update automatically. To have that happen you need your data saved in a database, with a trigger to recalculate attributes such as area each time the table is updated. – Micha Jul 1 '14 at 20:24
  • For QGIS 3 see this answer: gis.stackexchange.com/a/334345/35561 – Mr. Che Sep 9 at 12:23
4

You can enable automatic updates of feature attributes with the following PyQGIS script.

In this example, say you have a polygon layer named myPolygons, which has, among others, fields named area and perimeter.

Copy and paste the code into the QGIS Python Console.

# Initialize required variables
myLayer = QgsMapLayerRegistry.instance().mapLayersByName( 'myPolygons' )[0]
areaField = myLayer.fieldNameIndex( 'area' )
perimeterField = myLayer.fieldNameIndex( 'perimeter' )

# Slot, updates field values
def updateFeatureAttrs( fId, geom=None ):
    f = myLayer.getFeatures( QgsFeatureRequest( fId ) ).next()    
    if not geom:
        geom = f.geometry() 
    myLayer.changeAttributeValue( fId, areaField, geom.area() )
    myLayer.changeAttributeValue( fId, perimeterField, geom.length() )

# Update feature attributes when new features are added or geometry changes
myLayer.featureAdded.connect( updateFeatureAttrs )
myLayer.geometryChanged.connect( updateFeatureAttrs )

Now, every time you add a new polygon to the myPolygons layer or modify any polygon from it, its corresponding attributes (area and perimeter) will be updated.

enter image description here

In another question, I posted an example with line features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.