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.
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityI 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.
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.
In another question, I posted an example with line features.