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?