That is pretty simple by using custom properties by the setCustomProperty()
method.
The below example adds a memory layer to the legend and set the "showFeatureCount" property to True (you can run it from pyqgis console):
## 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)
To get a specific property of the current layer (node layer) in layer tree you can use customProperty()
or customProperties()
to get all the stored properties for that layer:
myLayerNode.customProperty("showFeatureCount")
## the result is True
myLayerNode.customProperties()
## the result is a list [u'showFeatureCount']
UPDATE: 10.04.2018
Using QGIS 3.x you can use the mapLayersByName
method from QgsProject
class in this way:
layers = QgsProject.instance().mapLayersByName('my layer name')
Since you can have several layers in QGIS with the same name in the layers panel, the method above gives you a list of matching layers.
Before accessing any element in the layer list, you should check if the list has elements. If so you can access, for instance, its first element (layer) in this way:
if layers:
layer = layers[0]
Which would be the common case of having a single layer matching the name you searched for.
For QGIS 2.x:
You would just need to make sure your layer has a name you can distinguish from others. Instead of layer = self.iface.activeLayer()
, do:
layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
if lyr.name() == "YOUR_LAYER_NAME":
layer = lyr
break
If you don't trust the layer name (after all, it can be changed by the user at any time), you could try to check the layer source. If your layer is a Shapefile, you could check the path to the Shapefile, this way:
layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
if lyr.source() == "/path/to/shapefile.shp":
layer = lyr
break
EDIT: As @Jakob has pointed out in comments, you can write the first block in one line:
layerList = QgsMapLayerRegistry.instance().mapLayersByName("YOUR_LAYER_NAME")
Or:
layerList = [lyr for lyr in QgsMapLayerRegistry.instance().mapLayers().values() if lyr.name() == "YOUR_LAYER_NAME"]
Anyway, you would need to check that layerList
is not empty before accessing its first element:
if layerList:
layer = layerList[0]
Best Answer
True
if layer exists, otherwiseFalse