In QGIS 2.18.19 I have a PostGIS Layer with a rule based render and activated show feature count. The feature count does not change automatically when doing some INSERTs (or DELETEs as well) directly into the layers table in the database (likely same applies when e.g. replacing a source shapefile).

I think that such cases are handled with a my_layer.dataProvider().forceReload() and there is a couple of ways as well to repaint the layer in the canvas like my_layer.triggerRepaint() or iface.mapCanvas().refreshAllLayer()) and even refresh the layer symbology in the legend (iface.layerTreeView().refreshLayerSymbology(my_layer.id())) but in all these refreshes there seems to be NO WAY to refresh the feature count.

Exception: I noticed, that over the GUI the only way to refresh feature count reliably for the layer itself and all its style rules is to go to Layer properties, set up a feature filter (simple expression True) and then reset the filter. By clicking Ok or Apply feature count refreshes as desired, but I need to do this programmatically.

I tried reproducing the feature filter in PyQGIS like


with no effect.

After days and nights of reading source codes I was not able to figure out whats updating feature count when pressing Ok in the layer properties dialog, perhaps anyone could give me some advice...

Question: How can I generally update/refresh feature count in such case with PyQGIS?

  • Maybe this helps link Mar 29, 2018 at 12:38
  • nope, doesn't, since turning on/off feature count in the legend does not refesh/update feature count. Apr 25, 2018 at 7:32

1 Answer 1


To my knowledge following line sets a new instance of source, name and providerType:

selectedLayer.setDataSource(selectedLayer.source(), selectedLayer.name(), selectedLayer.providerType())

As a result you get a new feature count as well. It's a good way for refreshing datasources changed outside the QGIS environment.

EDIT: As @Jochen Schwarze mentioned, the count number of categorized styles won't be affected and are still displaying the old count number. As a workaround you can simply copy and paste the style after refreshing the source:

  • +1 does this also affect feature count in categorized an rule based style? Oct 26, 2018 at 8:52
  • 1
    That's right. Answer edited.
    – pascatl
    Oct 26, 2018 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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