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?
-
You might be dealing with a bug rather than a problem that other users can help with. Consider installing a different version of QGIS, and using a new profile and see if you can replicate the issue. If you can, perhaps raise a bug (qgis.org/en/site/getinvolved/development/bugreporting.html)Tom Brennan– Tom Brennan2023年03月31日 03:47:57 +00:00Commented Mar 31, 2023 at 3:47
-
Check "startup.py" file in your home folder (something like ..AppData\Roaming\QGIS\QGIS3). Code in this file runs automatically on QGIS start. Check PYQGIS_STARTUP environment variable also.RainForest– RainForest2023年03月31日 08:45:01 +00:00Commented Mar 31, 2023 at 8:45
-
1When and where are you executing the code?Matt– Matt2023年03月31日 09:57:08 +00:00Commented Mar 31, 2023 at 9:57
1 Answer 1
After some time away from qgis scripts, this is the solution I found:
Apparently, when you try to add a python script file to QGIS "add scripts to toolbox", it gets coppied to qgis scripts folder and executed on startup.
In windows, go to: C:\Users\User\AppData\Roaming\QGIS\QGIS3\profiles\default\processing\scripts
and remove your personal scripts that are wrongly being executed on startup.
Version of QGIS tested: 3.22.14