Tell me please how to get the layer by name

QGIS 3.0

closed as unclear what you're asking by tinlyx, whyzar, aldo_tapia, ahmadhanb, nmtoken Apr 10 '18 at 19:23

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


I get layer by name in that way in QGIS3:

layer_list = QgsProject.instance().layerTreeRoot().children() # returns QgsLayerTreeNode object list
layer = [lyr.layer() for lyr in layer_list if lyr.name()=="LAYER_NAME"][0]

# OUT: <qgis._core.QgsVectorLayer object at ...>

I don't know if there is a shorter way. Maybe.

But in that way, you can get first layer named "LAYER_NAME". children() function doesn't return layers in a group layer.

EDIT: the shortest way of getting layer by name:

layers = QgsProject.instance().mapLayersByName('LAYER_NAME') # list of layers named LAYER_NAME
layer = layers[0] # first layer named LAYER_NAME.

If you are sure there is one "LAYER_NAME" then:

layer = QgsProject.instance().mapLayersByName('LAYER_NAME')[0]

Retrieve a list of matching registered layers by layer name.

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