Outdated version of the documentation. Find the latest one here.

レイヤーをロードする

データのレイヤーを開きましょう。QGISはベクターおよびラスターレイヤーを認識できます。加えてカスタムレイヤータイプを利用することもできますが、それについてここでは述べません.

ベクターレイヤー

To load a vector layer, specify layer’s data source identifier, name for the layer and provider’s name:

layer = QgsVectorLayer(data_source, layer_name, provider_name)
if not layer.isValid():
  print "Layer failed to load!"

データソース識別子は文字列でそれぞれのデータプロバイダーを表します。レイヤー名はレイヤーリストウィジェットの中で使われます。レイヤーが正常にロードされたかどうかをチェックすることは重要です。正しくロードされていない場合は不正なレイヤーインスタンスが返ります。

The quickest way to open and display a vector layer in QGIS is the addVectorLayer function of the QgisInterface:

layer = iface.addVectorLayer("/path/to/shapefile/file.shp", "layer name you like", "ogr")
if not layer:
  print "Layer failed to load!"

This creates a new layer and adds it to the map layer registry (making it appear in the layer list) in one step. The function returns the layer instance or None if the layer couldn’t be loaded.

以下のリストはベクターデータプロバイダーを使って様々なデータソースにアクセスする方法が記述されています.

  • OGR library (shapefiles and many other file formats) — data source is the path to the file:

    • for shapefile:

      vlayer = QgsVectorLayer("/path/to/shapefile/file.shp", "layer_name_you_like", "ogr")
      
    • for dxf (note the internal options in data source uri):

      uri = "/path/to/dxffile/file.dxf|layername=entities|geometrytype=Point"
      vlayer = QgsVectorLayer(uri, "layer_name_you_like", "ogr")
      
  • PostGIS database — data source is a string with all information needed to create a connection to PostgreSQL database. QgsDataSourceURI class can generate this string for you. Note that QGIS has to be compiled with Postgres support, otherwise this provider isn’t available:

    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")
    

    ノート

    uri.uri(False) に渡される False 引数は、認証構成パラメーターの拡張を防ぎます。もし何も認証構成を使用していなければ、この引数は何の違いもありません。

  • CSV or other delimited text files — to open a file with a semicolon as a delimiter, with field “x” for x-coordinate and field “y” for y-coordinate you would use something like this:

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

    ノート

    プロバイダーの文字列はURLとして構造化されているので、パスには file:// という接頭辞を付ける必要があります。また、 xy フィールドの代わりにWKT(well-known text)形式のジオメトリを使用でき、座標参照系を指定できます。例えば:

    uri = "file:///some/path/file.csv?delimiter=%s&crs=epsg:4723&wktField=%s" % (";", "shape")
    
  • GPXファイル—「GPX」データプロバイダーは、GPXファイルからトラック、ルートやウェイポイントを読み込みます。ファイルを開くには、タイプ(トラック/ルート/ウェイポイント)をURLの一部として指定する必要があります:

    uri = "path/to/gpx/file.gpx?type=track"
    vlayer = QgsVectorLayer(uri, "layer name you like", "gpx")
    
  • SpatiaLite database — Similarly to PostGIS databases, QgsDataSourceURI can be used for generation of data source identifier:

    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')
    
  • MySQLのWKBベースジオメトリ、OGR経由 — データソースはテーブルへの接続文字列です。

    uri = "MySQL:dbname,host=localhost,port=3306,user=root,password=xxx|layername=my_table"
    vlayer = QgsVectorLayer( uri, "my table", "ogr" )
    
  • WFS接続:. 接続は、URIと 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")
    

    URIは標準の 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))
    

ノート

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

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

ラスターレイヤー

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 file name and base name:

fileName = "/path/to/raster/file.tif"
fileInfo = QFileInfo(fileName)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(fileName, baseName)
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:

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

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

ラスターレイヤーも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')

detailed URI settings can be found in provider documentation

別の方法としては、WMSサーバーからラスターレイヤーを読み込むことができます。しかし現在では、 APIからGetCapabilitiesレスポンスにアクセスすることはできません—どのレイヤが必要か知っている必要があります。

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!"

Map Layer Registry

If you would like to use the opened layers for rendering, do not forget to add them to map layer registry. The map layer registry 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 map layer registry, it gets deleted, too.

Adding a layer to the registry:

QgsMapLayerRegistry.instance().addMapLayer(layer)

Layers are destroyed automatically on exit, however if you want to delete the layer explicitly, use:

QgsMapLayerRegistry.instance().removeMapLayer(layer_id)

For a list of loaded layers and layer ids, use:

QgsMapLayerRegistry.instance().mapLayers()