Using a Python script, I create a layer from a CSV file and then write it out to a gpkg file.
I then create a group in the layer tree, load it in the gpkg file and add it as a child of the group. This all works fine.
If I then save my project, close the project and then open the project again, then the gpkg layer in the group just appears as a title, there is no geometry associated with the layer any more.
So basically it is this in the script
uri = f"file:///{csv_path}?delimiter=,&wktField=geometry&crs=EPSG:4326"
wkt_layer = QgsVectorLayer(uri, layer_name, 'delimitedtext')
# Save to GeoPackage
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.layerName = layer_name
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile
error = QgsVectorFileWriter.writeAsVectorFormatV3(wkt_layer, gpkg_path, QgsCoordinateTransformContext(), options)
group = root.insertGroup(0, name)
wkt_layer = QgsVectorLayer(wkt_layer_path, f"{csv['name']} Route", "ogr")
group.addLayer(wkt_layer)
As I say, this works fine, until I save/close/reopen the project and then it only shows as the layer title without any geometry.
I can add the gpkg file again manually as there is nothing wrong with the produced file. After I had added the layer via the script, I also tried manually checking that the source was correct, which it was. And even applied to the properties. But this doesn't help fix the issue.
I feel like I am missing a step in telling QGIS about this new layer I have added to it.
wkt_layer_path
and shouldn't it begpkg_path
?QgsProject.instance().addMapLayer(wkt_layer, False) group.insertChildNode(-1, QgsLayerTreeLayer(wkt_layer))
Works as expected.