Geographic Information Systems Asked by rheras on June 2, 2021
Through PyQGIS using QgsVectorFileWriter.writeAsVectorFormat()
we can store a vector layer as .gpkg, is great!
However, once we close the project and reopen it again, the layer name is showed but their associated gpkg data are lost.
QGIS provide a way to permanently store a memory layer on disk, but it seems this is a manual process through the QGIS tool environment (context menu on every layer).
I’d like to export the layer using writeAsVectorFormat()
but as next stemp mark it as exported, so it would be available in the future even if I close the project.
Therefore, the ‘memory icon’ would disappear too.
Does anybody know it this is feasible using PyQGIS?
One approach to do it. Check if in memory layer, run processing script to save your "in memory" layer, change memory layer datasource and save your project.
In your case, you need to adapt my code to reuse infos like datasource path and layer name after your writeAsVectorFormat
export
project = QgsProject.instance()
project_dir_path = project.readPath("./")
for layer in project.mapLayers().values():
if layer.type() == QgsMapLayer.VectorLayer and layer.dataProvider().name() == 'memory':
# We do not manage sanitized name colision (if your
# layer name is the same, code will try to write to
# a GPKG with the same name and the same layer...)
layer_name = layer.name().lower().replace(' ', '_')
out = processing.run("native:savefeatures", {
'INPUT': iface.activeLayer(),
'OUTPUT': f'{project_dir_path}/{layer_name}.gpkg',
'LAYER_NAME':'',
'DATASOURCE_OPTIONS':'',
'LAYER_OPTIONS':''}
)
layer.setDataSource(f"{out['OUTPUT']}|layername={layer_name}", layer.name(), 'ogr')
project.write()
Answered by ThomasG77 on June 2, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP