The code snippets on this page need the following imports if you’re outside the pyqgis console:

1from qgis.core import (
2    QgsProject,
3    QgsPathResolver
4)
5
6from qgis.gui import (
7    QgsLayerTreeMapCanvasBridge,
8)

2. Caricamento di progetti

Ti può capitare di dovere caricare un progetto esistente da un plugin o (più spesso) quando stai sviluppando un’applicazione QGIS Python autonoma (see: Applicazioni Python).

Per caricare un progetto nell’applicazione QGIS corrente devi creare un’istanza della classe QgsProject. Questa è una classe singleton, quindi devi utilizzare il suo metodo instance() per farlo. Puoi chiamare il suo metodo read(), indicando il percorso del progetto da caricare:

 1# If you are not inside a QGIS console you first need to import
 2# qgis and PyQt classes you will use in this script as shown below:
 3from qgis.core import QgsProject
 4# Get the project instance
 5project = QgsProject.instance()
 6# Print the current project file name (might be empty in case no projects have been loaded)
 7# print(project.fileName())
 8
 9# Load another project
10project.read('testdata/01_project.qgs')
11print(project.fileName())
testdata/01_project.qgs

Se vuoi modificare il progetto (ad esempio per aggiungere o rimuovere dei layer) e salvare le modifiche, chiama il metodo write() dell’istanza del progetto. Il metodo write() accetta anche un nuovo percorso per salvare il progetto in una nuova posizione:

# Save the project to the same
project.write()
# ... or to a new file
project.write('testdata/my_new_qgis_project.qgs')

Sia la funzione read() che quella write() restituiscono un valore booleano che puoi utilizzare per verificare se l’operazione ha avuto esito positivo.

Nota

Se stai scrivendo un’applicazione QGIS, per sincronizzare il progetto caricato con l’area di mappa, devi creare un’istanza di QgsLayerTreeMapCanvasBridge come nell’esempio seguente:

bridge = QgsLayerTreeMapCanvasBridge( \
         QgsProject.instance().layerTreeRoot(), canvas)
# Now you can safely load your project and see it in the canvas
project.read('testdata/my_new_qgis_project.qgs')

2.1. Resolving bad paths

It can happen that layers loaded in the project are moved to another location. When the project is loaded again all the layer paths are broken.

The QgsPathResolver class with the setPathPreprocessor() allows setting a custom path pre-processor function, which allows for manipulation of paths and data sources prior to resolving them to file references or layer sources.

The processor function must accept a single string argument (representing the original file path or data source) and return a processed version of this path.

The path pre-processor function is called before any bad layer handler.

Some use cases:

  1. replace an outdated path:

    def my_processor(path):
        return path.replace('c:/Users/ClintBarton/Documents/Projects', 'x:/Projects/')
    
    QgsPathResolver.setPathPreprocessor(my_processor)
    
  2. replace a database host address with a new one:

    def my_processor(path):
        return path.replace('host=10.1.1.115', 'host=10.1.1.116')
    
    QgsPathResolver.setPathPreprocessor(my_processor)
    
  3. replace stored database credentials with new ones:

    1def my_processor(path):
    2    path= path.replace("user='gis_team'", "user='team_awesome'")
    3    path = path.replace("password='cats'", "password='g7as!m*'")
    4    return path
    5
    6QgsPathResolver.setPathPreprocessor(my_processor)