Chargement de couches

Le fragment de code sur cette page nécessite les importations suivantes:

import os # This is is needed in the pyqgis console also
from qgis.core import (
    QgsVectorLayer
)

Ouvrons donc quelques couches de données. QGIS reconnaît les couches vectorielles et raster. En plus, des types de couches personnalisés sont disponibles mais nous ne les aborderons pas ici.

Couches vectorielles

Pour créer une instance de couche vectorielle, spécifier l’identifiant de la source de données de la couche, le nom pour la couche et le nom du fournisseur de données:

# get the path to the shapefile e.g. /home/project/data/ports.shp
path_to_ports_layer = os.path.join(QgsProject.instance().homePath(), "data", "ports", "ports.shp")

# The format is:
# vlayer = QgsVectorLayer(data_source, layer_name, provider_name)

vlayer = QgsVectorLayer(path_to_ports_layer, "Ports layer", "ogr")
if not vlayer.isValid():
    print("Layer failed to load!")

L’identifiant de source de données est une chaîne de texte, spécifique à chaque type de fournisseur de données vectorielles. Le nom de la couche est utilisée dans le widget liste de couches. Il est important de vérifier si la couche a été chargée ou pas. Si ce n’était pas le cas, une instance de couche non valide est retournée.

Pour une couche vectorielle geopackage:

# get the path to a geopackage  e.g. /home/project/data/data.gpkg
path_to_gpkg = os.path.join(QgsProject.instance().homePath(), "data", "data.gpkg")
# append the layername part
gpkg_places_layer = path_to_gpkg + "|layername=places"
# e.g. gpkg_places_layer = "/home/project/data/data.gpkg|layername=places"
vlayer = QgsVectorLayer(gpkg_places_layer, "Places layer", "ogr")
if not vlayer.isValid():
    print("Layer failed to load!")

La méthode la plus rapide pour ouvrir et afficher un couche vectorielle dans QGIS est addVectorLayer() de la classe QgisInterface:

vlayer = iface.addVectorLayer(path_to_ports_layer, "Ports layer", "ogr")
if not vlayer:
  print("Layer failed to load!")

Cela crée une nouvelle couche et l’ajoute au projet QGIS courant (la faisant apparaître dans la liste des couches) en une seule étape. Cette fonction renvoie une instance de la couche ou None si la couche n’a pas pu être chargée.

La liste suivante montre comment accéder à différentes sources de données provenant de différents fournisseurs de données vectorielles:

  • la bibliothèque OGR (shapefile et de nombreux autres formats de fichiers) — La source de données est le chemin vers le fichier:

    • pour un shapefile:

      vlayer = QgsVectorLayer("/path/to/shapefile/file.shp", "layer_name_you_like", "ogr")
      
    • pour un dxf (notez les options internes dans l’uri de la source de données) :

      uri = "/path/to/dxffile/file.dxf|layername=entities|geometrytype=Point"
      vlayer = QgsVectorLayer(uri, "layer_name_you_like", "ogr")
      
  • Base de données PostGIS - La source de données est une chaîne de caractères data source contenant toute l’information nécessaire pour établir une connexion avec la base PostgreSQL.

    La classe QgsDataSourceUri peut générer cette chaîne de caractères pour vous. Notez que QGIS doit être compilé avec le support postgreSQL, faute de quoi le fournisseur ne sera pas disponible:

    uri = QgsDataSourceUri()
    # set host name, port, database name, username and password
    uri.setConnection("localhost", "5432", "dbname", "johny", "xxx")
    # set database schema, table name, geometry column and optionally
    # subset (WHERE clause)
    uri.setDataSource("public", "roads", "the_geom", "cityid = 2643")
    
    vlayer = QgsVectorLayer(uri.uri(False), "layer name you like", "postgres")
    

    Note

    L’argument False passé à uri.uri(False) empêche l’expansion des paramètres du système d’authentification. si vous n’avez pas configuré d’authentification, cet argument n’a aucun effet.

  • fichiers CSV et autres fichiers avec délimiteurs —Pour ouvrir un fichier avec des points virgules comme séparateurs, contenant des champs « x » pour les coordonnées X et « y » pour les coordonnées Y, vous devriez faire ceci:,

    uri = "/some/path/file.csv?delimiter={}&xField={}&yField={}".format(";", "x", "y")
    vlayer = QgsVectorLayer(uri, "layer name you like", "delimitedtext")
    

    Note

    La chaîne de texte du fournisseur de données est structuré comme une URL, le chemin doit ainsi être préfixé avec file://. Il permet aussi d’utiliser les géométries formatées en WKT (well-known text) à la place des champs x et y, et permet de spécifier le Système de Coordonnées de Référence. Par exemple :

    uri = "file:///some/path/file.csv?delimiter={}&crs=epsg:4723&wktField={}".format(";", "shape")
    
  • Fichiers GPS — le fournisseur de données « gpx » lit les trajets, routes et points de passage d’un fichier gpx. Pour ouvrir un fichier, le type (trajet/route/point) doit être fourni dans l’url :

    uri = "path/to/gpx/file.gpx?type=track"
    vlayer = QgsVectorLayer(uri, "layer name you like", "gpx")
    
  • Base de données spatialite — De manière similaire aux bases de données PostGIS, QgsDataSourceUri peut être utilisé pour générer l’identifiant de la source de données:

    uri = QgsDataSourceUri()
    uri.setDatabase('/home/martin/test-2.3.sqlite')
    schema = ''
    table = 'Towns'
    geom_column = 'Geometry'
    uri.setDataSource(schema, table, geom_column)
    
    display_name = 'Towns'
    vlayer = QgsVectorLayer(uri.uri(), display_name, 'spatialite')
    
  • Géométries MySQL basées sur WKB, avec OGR — la source des données est la chaîne de connexion à la table :

    uri = "MySQL:dbname,host=localhost,port=3306,user=root,password=xxx|layername=my_table"
    vlayer = QgsVectorLayer( uri, "my table", "ogr" )
    
  • Connexion WFS : la connexion est définie par une URI et utilise le fournisseur de données WFS

    uri = "http://localhost:8080/geoserver/wfs?srsname=EPSG:23030&typename=union&version=1.0.0&request=GetFeature&service=WFS",
    vlayer = QgsVectorLayer(uri, "my wfs layer", "WFS")
    

    L’uri peut être crée en utilisant la bibliothèque standard urllib:

    params = {
        'service': 'WFS',
        'version': '1.0.0',
        'request': 'GetFeature',
        'typename': 'union',
        'srsname': "EPSG:23030"
    }
    uri = 'http://localhost:8080/geoserver/wfs?' + urllib.unquote(urllib.urlencode(params))
    

Note

You can change the data source of an existing layer by calling setDataSource() on a QgsVectorLayer instance, as in the following example:

# vlayer is a vector layer, uri is a QgsDataSourceUri instance
vlayer.setDataSource(uri.uri(), "layer name you like", "postgres")

Couches raster

For accessing raster files, GDAL library is used. It supports a wide range of file formats. In case you have troubles with opening some files, check whether your GDAL has support for the particular format (not all formats are available by default). To load a raster from a file, specify its filename and display name:

# get the path to a tif file  e.g. /home/project/data/srtm.tif
path_to_tif = os.path.join(QgsProject.instance().homePath(), "data", "srtm.tif")
rlayer = QgsRasterLayer(path_to_tif, "SRTM layer name")
if not rlayer.isValid():
    print("Layer failed to load!")

To load a raster from a geopackage:

# get the path to a geopackage  e.g. /home/project/data/data.gpkg
path_to_gpkg = os.path.join(QgsProject.instance().homePath(), "data", "data.gpkg")
# gpkg_raster_layer = "GPKG:/home/project/data/data.gpkg:srtm"
gpkg_raster_layer = "GPKG:" + path_to_gpkg + ":srtm"

rlayer = QgsRasterLayer(gpkg_raster_layer, "layer name you like", "gdal")

if not rlayer.isValid():
    print("Layer failed to load!")

Similarly to vector layers, raster layers can be loaded using the addRasterLayer function of the QgisInterface object:

iface.addRasterLayer("/path/to/raster/file.tif", "layer name you like")

This creates a new layer and adds it to the current project (making it appear in the layer list) in one step.

Les couches raster peuvent également être créées à partir d’un service WCS.

layer_name = 'modis'
uri = QgsDataSourceUri()
uri.setParam('url', 'http://demo.mapserver.org/cgi-bin/wcs')
uri.setParam("identifier", layer_name)
rlayer = QgsRasterLayer(str(uri.encodedUri()), 'my wcs layer', 'wcs')

Here is a description of the parameters that the WCS URI can contain:

WCS URI is composed of key=value pairs separated by &. It is the same format like query string in URL, encoded the same way. QgsDataSourceUri should be used to construct the URI to ensure that special characters are encoded properly.

  • url (required) : WCS Server URL. Do not use VERSION in URL, because each version of WCS is using different parameter name for GetCapabilities version, see param version.

  • identifier (required) : Coverage name

  • time (optional) : time position or time period (beginPosition/endPosition[/timeResolution])

  • format (optional) : Supported format name. Default is the first supported format with tif in name or the first supported format.

  • crs (optional) : CRS in form AUTHORITY:ID, e.g. EPSG:4326. Default is EPSG:4326 if supported or the first supported CRS.

  • username (optional) : Username for basic authentication.

  • password (optional) : Password for basic authentication.

  • IgnoreGetMapUrl (optional, hack) : If specified (set to 1), ignore GetCoverage URL advertised by GetCapabilities. May be necessary if a server is not configured properly.

  • InvertAxisOrientation (optional, hack) : If specified (set to 1), switch axis in GetCoverage request. May be necessary for geographic CRS if a server is using wrong axis order.

  • IgnoreAxisOrientation (optional, hack) : If specified (set to 1), do not invert axis orientation according to WCS standard for geographic CRS.

  • cache (optional) : cache load control, as described in QNetworkRequest::CacheLoadControl, but request is resend as PreferCache if failed with AlwaysCache. Allowed values: AlwaysCache, PreferCache, PreferNetwork, AlwaysNetwork. Default is AlwaysCache.

Vous pouvez aussi charger une couche raster à partir d’un serveur WMS. Il n’est cependant pas encore possible d’avoir accès à la réponse de GetCapabilities à partir de l’API — vous devez connaître les couches que vous voulez :

urlWithParams = 'url=http://irs.gis-lab.info/?layers=landsat&styles=&format=image/jpeg&crs=EPSG:4326'
rlayer = QgsRasterLayer(urlWithParams, 'some layer name', 'wms')
if not rlayer.isValid():
  print("Layer failed to load!")

QgsProject instance

If you would like to use the opened layers for rendering, do not forget to add them to the QgsProject instance. The QgsProject instance takes ownership of layers and they can be later accessed from any part of the application by their unique ID. When the layer is removed from the project, it gets deleted, too. Layers can be removed by the user in the QGIS interface, or via Python using the removeMapLayer() method.

Adding a layer to the current project is done using the addMapLayer() method:

QgsProject.instance().addMapLayer(rlayer)

To add a layer at an absolute position:

# first add the layer without showing it
QgsProject.instance().addMapLayer(rlayer, False)
# obtain the layer tree of the top-level group in the project
layerTree = iface.layerTreeCanvasBridge().rootGroup()
# the position is a number starting from 0, with -1 an alias for the end
layerTree.insertChildNode(-1, QgsLayerTreeLayer(rlayer))

If you want to delete the layer use the removeMapLayer() method:

# QgsProject.instance().removeMapLayer(layer_id)
QgsProject.instance().removeMapLayer(rlayer.id())

In the above code, the layer id is passed (you can get it calling the id() method of the layer), but you can also pass the layer object itself.

For a list of loaded layers and layer ids, use the mapLayers() method:

QgsProject.instance().mapLayers()