6

After adding a layer to my QGIS project with a Python script, I want to show the number of objects beside the layer in the layer window.

I have tried this code, which is from

Show feature count of layer via Python console / PyQGIS

to see if it works in QGIS 3.

## create the memory layer and add to the registry
myLayer = QgsVectorLayer("Point", "myLayer", "memory")
QgsMapLayerRegistry.instance().addMapLayer(myLayer, False)

## reference to the layer tree
root = QgsProject.instance().layerTreeRoot()

## adds the memory layer to the layer node at index 0
myLayerNode = QgsLayerTreeLayer(myLayer)
root.insertChildNode(0, myLayerNode)

## set custom property
myLayerNode.setCustomProperty("showFeatureCount", True)

The module QgsMapLayerRegistry seems to have changed from QGIS 2 to QGIS 3, because when I enter >>>help(QgsMapLayerRegistry), I am getting this error message:

help(QgsMapLayerRegistry)
Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
NameError: name 'QgsMapLayerRegistry' is not defined

I also tried to use the method showFeatureCount() on my freshly created layer, but that didn't work either.

mem_layer = QgsVectorLayer(uri, 'my_file', 'delimitedtext')
        QgsProject.instance().addMapLayer(mem_layer)
        mem_layer.loadNamedStyle(r"P:\my_style.qml")
        mem_layer.showFeatureCount()
        mem_layer.triggerRepaint()

What do I need to change to make the code work?

1 Answer 1

7

In QGIS 3, QgsMapLayerRegistry() has been replaced by QgsProject(). You can find more information about backwards compatibility here.

To show the feature count of a newly-added layer, you could use something like the following:

mem_layer = QgsVectorLayer(uri, 'my_file', 'delimitedtext')
QgsProject.instance().addMapLayer(mem_layer)
mem_layer.loadNamedStyle(r"P:\my_style.qml")
mem_layer.triggerRepaint()

# Show Feature Count
root = QgsProject.instance().layerTreeRoot()
myLayerNode = root.findLayer(mem_layer.id())
myLayerNode.setCustomProperty("showFeatureCount", True)

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.