I'm trying to write a Python script (QGis 3.4.9) to create a group of scratch-layers (polygon, line and point). When it is inside the function the layer is created as it should, but when the function is done the geometry (and anything else it seems) is gone. The layer is there but no geometry. I'm clearly missing something?
def scratch_group():
isthere = False
sgroupname = "Scratch_group"
root = QgsProject.instance().layerTreeRoot()
for child in root.children():
if isinstance(child, QgsLayerTreeGroup):
if child.name().upper() == sgroupname.upper():
isthere = True
print("- group: " + child.name() + " already there")
if not isthere:
root = QgsProject.instance().layerTreeRoot()
sgroup = root.addGroup(sgroupname)
stiep = "point"
slayerp= QgsVectorLayer(stiep, "Scratch_point", "memory")
sgroup.insertChildNode(0, QgsLayerTreeLayer(slayerp))
slayerp.startEditing()
QMessageBox.information(iface.mainWindow(),"Check","Geometry",QMessageBox.Ok)
return()
#---main---
scratch_group()
QMessageBox.information(iface.mainWindow(),"Check","If Geometry is gone",QMessageBox.Ok)
EDIT: In the meantime i stumbled on Adding layer to group in layers panel using PyQGIS? You have to create a clone of the layer put it in place and remove the original. That partially solved it:
def create_memlayer_ingroup(stiep, sname, sgroup):
vlayer = QgsVectorLayer(stiep, sname,"memory")
QgsProject.instance().addMapLayer(vlayer)
root = QgsProject.instance().layerTreeRoot()
ilayer = root.findLayer(vlayer.id())
clone = ilayer.clone()
sgroup.insertChildNode(0, clone)
print(ilayer)
root.removeChildNode(ilayer)
def create_sgroup(gname):
rt = QgsProject.instance().layerTreeRoot()
return(rt.addGroup(gname))
memgroup = create_sgroup("Scratch_group2")
create_memlayer_ingroup("Polygon", "Scratch_Polygon", memgroup)
create_memlayer_ingroup("Linestring", "Scratch_line", memgroup)
create_memlayer_ingroup("Point", "Scratch_point", memgroup)
This works when the group is not placed at the top of the tree. When it is at top (if no other layer is opened), the second and third memlayer is opened twice within the group. So not perfect yet...