I am in the process of writing my two first QGIS plugins. (https://github.com/sickel/qgisSpectre and https://github.com/sickel/qgisstripchart) Bothboth of them contains two drop down boxes, one to select a layer, and then the other is populated with the fields from the layer when a layer is selected.
For this, I want to just list the vector layers in the first dropdown. After some fooling around, I ended up doing it like this, which feels like going around in circles:
layers = QgsProject.instance().layerTreeRoot().children()
self.dlg.cbLayer.clear()
for layeritem in layers:
layername=layeritem.name()
layers = QgsProject.instance().mapLayersByName(layername)
if len(layers)==0: # Invalid layer name
return
layer = layers[0] # first layer .
if "fields" in dir(layer):
self.dlg.cbLayer.addItems([layer.name()])
layers = QgsProject.instance().layerTreeRoot().children()
self.dlg.cbLayer.clear()
for layeritem in layers:
layername=layeritem.name()
layers = QgsProject.instance().mapLayersByName(layername)
if len(layers)==0: # Invalid layer name
return
layer = layers[0] # first layer
if "fields" in dir(layer):
self.dlg.cbLayer.addItems([layer.name()])
So I am getting the layer names from layerTreeRoot().children()layerTreeRoot().children()
, then I am using that name to pick up the layer from mapLayersByNamemapLayersByName
.
Is there aa way to
either either Get the layer directly from layerTreeRoot().children()layerTreeRoot().children()
or Iterate over the map layers in another way, e.g through QgsProject.instance().mapLayers() and through QgsProject.instance().mapLayers()
and get each layerslayer's type and name?
(Another problem my current code has, is that it will not list layers inside a group, I think this may work fine if I can get what I need from QgsProject.instance().mapLayers()QgsProject.instance().mapLayers()
)