如何使用Python在QGIS中切换图层可见性?


12

如何通过Python API在QGIS中切换图层可见性?

Answers:


11

如果您正在运行QGIS => 1.5,则来自QGIS文档

from PyQt4 import QtCore, QtGui
from qgis import core, gui
i = qgis.utils.iface
# load a georeferenced raster layer
loadedLayer = i.addRasterLayer('c:\\data\\a_map.png')
# get legend
legend = i.legendInterface()
# check current visibility
legend.isLayerVisible(loadedLayer)
# set visibility off 
legend.setLayerVisible(loadedLayer, False)
# and on again!
legend.setLayerVisible(loadedLayer, True) 

我想您将只交换loadedLayer = i.addRasterLayer('c:\\data\\a_map.png')要隐藏的图层,可以使用类似以下的方法:

QgsMapLayerRegistry.instance().mapLayer(QString theLayerId)

0

接受的答案不适用于QGIS3。在QGIS3中,我使用以下代码:

QgsProject.instance().layerTreeRoot().findLayer(lyr.id()).setItemVisibilityChecked(False)

另外,我们可以通过以下方式打开和关闭所有图层:

bool = True # or False
root = QgsProject.instance().layerTreeRoot()
allLayers = root.layerOrder()
for layer in allLayers:
    root.findLayer(layer.id()).setItemVisibilityChecked(bool)


您的第一个代码块不是切换开关,而是显式地将目标层设置为不可见。
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.