1

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.

3
  • 3
    What is wkt_layer_path and shouldn't it be gpkg_path? Commented Jul 5 at 10:27
  • gpkg_path is the file name of the gpkg file. I figured it out with a bit more reading. I had missed adding the layer to the project , so it wasn't truly part of the project, it just appeared to be. The answer was to add the layer to the project without rendering it, and then add the layer to the group as a child node. Basically QgsProject.instance().addMapLayer(wkt_layer, False) group.insertChildNode(-1, QgsLayerTreeLayer(wkt_layer)) Works as expected.
    – John_nz
    Commented Jul 6 at 9:30
  • Nice! Please add that as your own answer and mark the question solved :) Commented Jul 6 at 14:28

1 Answer 1

2

I had missed adding the layer to the project, so it wasn't truly part of the project, it just appeared to be.

The answer was to add the layer to the project without rendering it, and then add the layer to the group as a child node.

Basically

QgsProject.instance().addMapLayer(wkt_layer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(wkt_layer))

works as expected.

Not the answer you're looking for? Browse other questions tagged or ask your own question.