I made a small code to fetch some PostGIS layers into QGIS and apply them with qml style, like the following:
import os
from qgis.core import QgsVectorLayer, QgsDataSourceUri, QgsVectorLayer, QgsProject
uri = QgsDataSourceUri()
uri.setConnection(#CONN_INFO)
city_filter = 'Cairu'
uri.setDataSource("public", "dende_mp", "geom", f"nom_munici = '{city_filter}'")
vlayer = QgsVectorLayer(uri.uri(False), f"car_{city_filter}", "postgres")
QgsProject.instance().addMapLayer(vlayer)
vlayer.loadNamedStyle('C:\\Users\\curyp\\OneDrive\\Desktop\\Projetos\\project_1\\styles\\tam_area_car.qml')
uri.setDataSource("public", "sigef_visita", "geom", f"municip = '{city_filter}'")
vlayer_sigef = QgsVectorLayer(uri.uri(False), f"sigef_{city_filter}", "postgres")
QgsProject.instance().addMapLayer(vlayer_sigef)
vlayer_sigef.loadNamedStyle('C:\\Users\\curyp\\OneDrive\\Desktop\\Projetos\\project_1\\styles\\tam_area_sigef.qml')
It's working fine, but for some reason after I close and reopen QGIS, these same layers get loaded again, with styling and all. It also asks me if I want to save or discard project modifications.
I've tried to delete layers, discard editings, calling QgsProject.instance().removeAllMaplayers()
, but none of these works.
Any ideas?