2

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?

Vince
  • 20,017
  • 15
  • 45
  • 64
Cupain
  • 695
  • 4
  • 17

2 Answers2

3

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)
J. Monticolo
  • 15,695
  • 1
  • 29
  • 64
  • Thank you, that's exactly what i needed. It counts the features of layers and categories, and add the result in their name. – Cupain Nov 27 '19 at 13:27
3

You can use collections.Counter.

from collections import Counter
layer = iface.activeLayer() # My layer 
field_categorized = 'category' # My categorized field 
c = Counter([feature[field_categorized] for feature in layer.getFeatures()]) # Loop on features of the layer 

# Result 
print(c)
Counter({0: 67, 1: 34})
Vincent Bré
  • 4,090
  • 7
  • 23
  • Thank you for the answer! I think it's ok to get one result for one particular category. But J. Monticolo's answer is more simple and add the result to the layer name – Cupain Nov 27 '19 at 13:29