If you have several options, you can combine them for different cases:
You can use QgsProject signals.
You have the signal cleared()
but as @Jaume Figueras points out it runs after closing.
You can complement it with projectSaved()
signal when the user during the execution clicks on save.
Since you are interested in saving the changes of the layers by code, it would be best to focus on them with.
The QgsProject signal, layersWillBeRemoved()
, when closing the project is triggered before removing the layers.
But I think the ideal option is to use the signals on the layers (QgsMapLayer
), specifically willBeDeleted ()
.
As the API indicates:
Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid state: the last chance for other pieces of code for some cleanup if they use the layer.
To connect the events on the layers you can generate a list of all the layers and with a cycle connect the signal:
pry= QgsProject.instance() #Capture the project
listLayers= list(pry.mapLayers().values())
for i in listLayers:
i.willBeDeleted.connect(self. your Functionyour_function)
To connect and disconnect the signals to the layers that are added and removed during execution you use the QgsProject
signals, layersWillBeRemoved
, layersAdded
, among others