Thursday, 17 September 2015

pyqgis - Count features in layers and categories


I want to automatically count features in my opened layers, and add the result in the layer name, with pyqgis. I can do it with this code :



layers = QgsProject.instance().mapLayers().values()
for layer in layers:
fc = layer.featureCount()
fc = str(fc)
layer.setName(layer.name()+" ["+fc+"]")

However, it does count features in each layer, but not in each renderer category when a layer have a categorized style. I was trying something like this just to print the result :


for layer in layers:
renderer = layer.renderer()
renderert = renderer.type()

if renderert == "categorizedSymbol":
for cat in renderer.categories():
print(cat.label+cat.featureCount())

But i get an "AttributeError: 'QgsRendererCategory' object has no attribute 'featureCount'"


Do you know how to apply the featureCount() function to layers and categories?



Answer



From this answer, is this code below a nicer solution ?


I just use the builtin layer function Show feature count :


layers = QgsProject.instance().mapLayers().values()

root = QgsProject.instance().layerTreeRoot()
for layer in layers:
if layer.type() == QgsMapLayer.VectorLayer:
myLayerNode = root.findLayer(layer.id())
myLayerNode.setCustomProperty("showFeatureCount", True)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...