In the layer tree, I want to move a few layers at root level to a group also at root level. From what I have gathered so far, I have to clone the layer first, add it to the group and then delete the original layer.
https://docs.qgis.org/3.4/en/docs/pyqgis_developer_cookbook/cheat_sheet.html#advanced-toc
So I am trying to fill the variables with the group and layers I want to work with.
The for-loop finds the group, but for some reason, I am getting None for the value of LyrOne.
from qgis.core import QgsLayerTreeGroup, QgsLayerTreeLayer
root = QgsProject.instance().layerTreeRoot()
for child in root.children():
if isinstance(child, QgsLayerTreeGroup):
print ("- group: " + child.name())
elif isinstance(child, QgsLayerTreeLayer):
print ("- layer: " + child.name())
grpQS = root.findGroup("QS")
LyrOne = root.findLayer("One")
print(QS_group)
print(LyrOne)
The results of the for-loop and the print statements are:
- layer: One
- group: QS
<qgis._core.QgsLayerTreeGroup object at 0x0000000008032A68>
None
Why can I get a reference to the group, but not for the layer?
EDIT: I managed to create a dictionary with the names of the layers as keys
dictLayer = {}
for child in root.children():
if isinstance(child, QgsLayerTreeLayer):
lyrName = child.name()
lyrID = child.layerId()
dictLayer[lyrName] = lyrID
LyrOne = dictLayer["One"]
Unfortunately, this solution Add layer to a QGIS group using Python
toc = self.iface.legendInterface()
groups = toc.groups()
groupIndex = groups.index(u'myGroup')
toc.moveLayer(newLayer, groupIndex)
doesn't work in QGIS3. How can I move a layer to a group in QGIS 3?
LyrOne_clone = LyrOne.clone()doesn't work :( – GISme Jul 22 '19 at 15:33<qgis._core.QgsVectorLayer object at 0x00000000193D2678>For root I got<qgis._core.QgsLayerTree object at 0x00000000080324C8>For mylayer I gotNone. So the rest of the code doesn't work, becauseAttributeError: NoneType object has no attribute clone– GISme Jul 23 '19 at 07:24root.findLayer(layer.id())then. This code is tested with QGIS 3.8 and works perfectly – Fran Raga Jul 23 '19 at 07:40