Important

Translation is a community effort you can join. This page is currently translated at 52.17%.

2. Chargement de projets

Indication

Les extraits de code sur cette page nécessitent les importations suivantes si vous êtes en dehors de la console pyqgis :

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

Vous avez parfois besoin de charger un projet existant depuis une extension ou (le plus souvent) lorsque vous développez une application QGIS autonome (voir Applications Python).

Pour charger un projet dans l’application QGIS courante, vous devez créer une instance de la classe QgsProject. C’est un objet singleton, ce qui vous impose d’utiliser sa méthode instance(). Vous pouvez appeler sa méthode read(), en lui passant le chemin du projet à charger:

 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

Si vous avez besoin de réaliser des modifications du projet (par exemple ajouter ou supprimer des couches) et de sauver vos changements, appelez la méthode write() de votre instance de projet. La méthode write() accepte également un chemin en option pour sauvegarder le projet à un nouvel emplacement:

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

Les deux fonctions read() et write() renvoient une valeur booléenne qui peut être utilisée pour vérifier que l’opération a réussi.

Note

Si vous codez une application QGIS autonome, afin de synchroniser le projet chargé avec le canevas il vous faut instancier QgsLayerTreeMapCanvasBridge comme dans l’exemple ci dessous:

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. Résoudre les mauvais chemins

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 helps you rewrite layers path within the project.

Its setPathPreprocessor() method allows setting a custom path pre-processor function to manipulate 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. If multiple preprocessors are set, they will be called in sequence based on the order in which they were originally set.

Quelques cas d’utilisation :

  1. remplacer un chemin qui n’est plus bon :

    def my_processor(path):
        return path.replace('c:/Users/ClintBarton/Documents/Projects', 'x:/Projects/')
    
    QgsPathResolver.setPathPreprocessor(my_processor)
    
  2. remplacer une adresse d’hôte de base de données par une nouvelle :

    def my_processor(path):
        return path.replace('host=10.1.1.115', 'host=10.1.1.116')
    
    QgsPathResolver.setPathPreprocessor(my_processor)
    
  3. remplacer les ids stockés dans la base de données par de nouveaux ids :

    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)
    

Likewise, a setPathWriter() method is available for a path writer function.

An example to replace the path with a variable:

def my_processor(path):
  return path.replace('c:/Users/ClintBarton/Documents/Projects', '$projectdir$')

QgsPathResolver.setPathWriter(my_processor)

Both methods return an id that can be used to remove the pre-processor or writer they added. See removePathPreprocessor() and removePathWriter().

2.2. Using flags to speed up things

In some instances where you may not need to use a fully functional project, but only want to access it for a specific reason, flags may be helpful. A full list of flags is available under ProjectReadFlag. Multiple flags can be added together.

As an example, if we do not care about actual layers and data and simply want to access a project (e.g. for layout or 3D view settings), we can use DontResolveLayers flag to bypass the data validation step and prevent the bad layer dialog from appearing. The following can be done:

readflags = Qgis.ProjectReadFlags()
readflags |= Qgis.ProjectReadFlag.DontResolveLayers
project = QgsProject()
project.read('C:/Users/ClintBarton/Documents/Projects/mysweetproject.qgs', readflags)

To add more flags the python Bitwise OR operator (|) must be used.