pyqgisコンソールの外部にいる場合、このページのコードスニペットでは以下のインポートが必要になります:
from qgis.core import (
QgsProject,
QgsVectorLayer,
)
4. 目次(TOC)へのアクセス¶
さまざまなクラスを使用して、TOCにロードされているすべてのレイヤーにアクセスし、それらを使用して情報を取得できます:
4.1. QgsProject クラス¶
You can use QgsProject
to retrieve information
about the TOC and all the layers loaded.
QgsProject
の「インスタンス」を作成し、そのメソッドを使用してロードされたレイヤーを取得する必要があります。
The main method is mapLayers()
. It will
return a dictionary of the loaded layers:
layers = QgsProject.instance().mapLayers()
print(layers)
{'countries_89ae1b0f_f41b_4f42_bca4_caf55ddbe4b6': <QgsVectorLayer: 'countries' (ogr)>}
The dictionary keys
are the unique layer ids while the values
are the
related objects.
It is now straightforward to obtain any other information about the layers:
1 2 3 4 5 6 7 8 | # list of layer names using list comprehension
l = [layer.name() for layer in QgsProject.instance().mapLayers().values()]
# dictionary with key = layer name and value = layer object
layers_list = {}
for l in QgsProject.instance().mapLayers().values():
layers_list[l.name()] = l
print(layers_list)
|
{'countries': <QgsVectorLayer: 'countries' (ogr)>}
You can also query the TOC using the name of the layer:
country_layer = QgsProject.instance().mapLayersByName("countries")[0]
注釈
一致するすべてのレイヤーを含むリストが返されるため、 [0]
でインデックスを作成して、この名前の最初のレイヤーを取得します。
4.2. QgsLayerTreeGroup クラス¶
レイヤーツリーは、ノードで構築された古典的なツリー構造です。現在、ノードには2つのタイプがあります:グループノード( QgsLayerTreeGroup
)とレイヤーノード( QgsLayerTreeLayer
)。
The project layer tree can be accessed easily with the method layerTreeRoot()
of the QgsProject
class:
root = QgsProject.instance().layerTreeRoot()
root
はグループノードであり、 子 を持っています:
root.children()
直接の子のリストが返されます。サブグループの子には、自分の直接の親からアクセスする必要があります。
We can retrieve one of the children:
child0 = root.children()[0]
print(child0)
<qgis._core.QgsLayerTreeLayer object at 0x7f1e1ea54168>
Layers can also be retrieved using their (unique) id
:
ids = root.findLayerIds()
# access the first layer of the ids list
root.findLayer(ids[0])
また、グループは名前を使用して検索することもできます:
root.findGroup('Group Name')
QgsLayerTreeGroup
has many other useful
methods that can be used to obtain more information about the TOC:
# list of all the checked layers in the TOC
checked_layers = root.checkedLayers()
print(checked_layers)
[<QgsVectorLayer: 'countries' (ogr)>]
Now let’s add some layers to the project’s layer tree. There are two ways of doing that:
Explicit addition using the
addLayer()
orinsertLayer()
functions:1 2 3 4 5 6
# create a temporary layer layer1 = QgsVectorLayer("path_to_layer", "Layer 1", "memory") # add the layer to the legend, last position root.addLayer(layer1) # add the layer at given position root.insertLayer(5, layer1)
Implicit addition: since the project's layer tree is connected to the layer registry it is enough to add a layer to the map layer registry:
QgsProject.instance().addMapLayer(layer1)
You can switch between QgsVectorLayer
and
QgsLayerTreeLayer
easily:
node_layer = root.findLayer(country_layer.id())
print("Layer node:", node_layer)
print("Map layer:", node_layer.layer())
Layer node: <qgis._core.QgsLayerTreeLayer object at 0x7f24423175e0>
Map layer: <QgsVectorLayer: 'countries' (ogr)>
グループは addGroup()
メソッドで追加できます。以下の例では、前者はTOCの最後にグループを追加し、後者の場合は既存のグループ内に別のグループを追加できます:
node_group1 = root.addGroup('Simple Group')
# add a sub-group to Simple Group
node_subgroup1 = node_group1.addGroup("I'm a sub group")
ノードとグループを移動するには、多くの便利な方法があります。
既存のノードの移動は、次の3つのステップで実行されます:
cloning the existing node
moving the cloned node to the desired position
deleting the original node
1 2 3 4 5 6 | # clone the group
cloned_group1 = node_group1.clone()
# move the node (along with sub-groups and layers) to the top
root.insertChildNode(0, cloned_group1)
# remove the original node
root.removeChildNode(node_group1)
|
It is a little bit more complicated to move a layer around in the legend:
1 2 3 4 5 6 7 8 9 10 11 12 | # get a QgsVectorLayer
vl = QgsProject.instance().mapLayersByName("countries")[0]
# create a QgsLayerTreeLayer object from vl by its id
myvl = root.findLayer(vl.id())
# clone the myvl QgsLayerTreeLayer object
myvlclone = myvl.clone()
# get the parent. If None (layer is not in group) returns ''
parent = myvl.parent()
# move the cloned layer to the top (0)
parent.insertChildNode(0, myvlclone)
# remove the original myvl
root.removeChildNode(myvl)
|
or moving it to an existing group:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # get a QgsVectorLayer
vl = QgsProject.instance().mapLayersByName("countries")[0]
# create a QgsLayerTreeLayer object from vl by its id
myvl = root.findLayer(vl.id())
# clone the myvl QgsLayerTreeLayer object
myvlclone = myvl.clone()
# create a new group
group1 = root.addGroup("Group1")
# get the parent. If None (layer is not in group) returns ''
parent = myvl.parent()
# move the cloned layer to the top (0)
group1.insertChildNode(0, myvlclone)
# remove the QgsLayerTreeLayer from its parent
parent.removeChildNode(myvl)
|
Some other methods that can be used to modify the groups and layers:
1 2 3 4 5 6 7 8 9 10 11 12 | node_group1 = root.findGroup("Group1")
# change the name of the group
node_group1.setName("Group X")
node_layer2 = root.findLayer(country_layer.id())
# change the name of the layer
node_layer2.setName("Layer X")
# change the visibility of a layer
node_group1.setItemVisibilityChecked(True)
node_layer2.setItemVisibilityChecked(False)
# expand/collapse the group view
node_group1.setExpanded(True)
node_group1.setExpanded(False)
|