2

In QGIS 3.22.10, I created a No Geometry layer and a group layer. The No Geometry layer was added to the group layer, and it was added perfectly. I can see the data in QGIS.

Here is the code for layer and group creation:

root = QgsProject.instance().layerTreeRoot()
group = root.addGroup('rel')
layer_info = {'id': '', 'c_comments': '' ,'scomment': ''}
fields = '&'.join(map(lambda x: f'field={x}:string(255)', layer_info.keys()))
temp_layer = QgsVectorLayer(f"None?crs=EPSG:4326&{fields}", f'comments', "memory")
myLayerNode = QgsLayerTreeLayer(temp_layer)
group.insertChildNode(0, myLayerNode)

However, when I try to read the layer with PyQGIS, I get a IndexError, even though the layer is available in QGIS.

QgsProject().instance().mapLayersByName('comments')[0]

Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS32~1.10\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
IndexError: list index out of range
2
  • 4
    You never added the layer to the project which you need to do. You can set the addToLegend argument to False e.g. QgsProject.instance().addMapLayer(temp_layer, False) then insert the node at desired position in group.
    – Ben W
    Commented Dec 2 at 10:28
  • 1
    Dear @BenW, I would suggest extending your comment as a valid answer
    – Taras
    Commented Dec 2 at 15:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.