Answers:
如果您正在运行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)
接受的答案不适用于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)