You can use the following code which connects the selectionChanged
event
(changing features in a layer) to a function. This function will only be applied to line and polygon type shapefiles already loaded into QGIS.
We can also make it so that the sum of the length and area of the selected features is calculated and printed instead of printing out separate values for each feature. Copy/paste the following into the Python Console then click a layer and select your features:
def calc_Geom():
layer = qgis.utils.iface.activeLayer()
# Get geometryType(): 0 = points; 1 = lines; 2 = polygons
if layer.geometryType() == 1:
length = 0
# Get total length
for f in layer.selectedFeatures():
length += f.geometry().length()
print "Length: " + str(length) + " m"
if layer.geometryType() == 2:
area = 0
# Get total area
for f in layer.selectedFeatures():
area += f.geometry().area()
print "Area: " + str(area) + " m^2"
else:
pass
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
if layer.geometryType() == 1 or layer.geometryType() == 2:
layer.selectionChanged.connect(calc_Geom)
Example (selected features highlighted yellow):