This is adapted from @CaptainDang's plugin and allows for you to save each layer to the single geopackage (qgis v3.22):
Usage example:
#overwrite any existing geopackages as this is the first layer I'm saving
self.saveAs_gpkg(tmpMemory_Layer, theGeopack, True)
# Sets the layer's data source to the newly created gpkg, replaces temp layer with the permanent one
tmpMemory_Layer.setDataSource(theGeopack + f'|layername={tmpMemory_Layer.name()}', tmpMemory_Layer.name(), 'ogr')
requirements:
from qgis import processing
code:
def saveAs_gpkg(self, styled_layer, theFileandPath, OptionsOverwriteFile):
#output_file = os.path.join(new_folder_path, layer_name + ".gpkg")
#if not os.path.exists(theFileandPath):
parameters = {
'LAYERS': [styled_layer],
'OUTPUT': theFileandPath + ".gpkg",
# Specify the output file with .gpkg extension
'OVERWRITE': OptionsOverwriteFile,
'SAVE_STYLES': True,
'SAVE_METADATA': True,
'SELECTED_FEATURES_ONLY': False,
'EXPORT_RELATED_LAYERS': False}
feedback = QgsProcessingFeedback()
# Execute the package algorithm
try:
result = processing.run("native:package", parameters, feedback=feedback)
if result['OUTPUT']:
pass
else:
iface.messageBar().pushMessage("Failed: ",
"layer '{}' was not saved.".format(
styled_layer.name()), level=2)
failedSaves.append(layer_name)
except QgsProcessingException as e:
iface.messageBar().pushMessage("Error: ",
"An error occurred while packaging layer '{}': '{}'".format(
styled_layer.name(), str(e)), level=2)