…when QGIS cannot do something by itself, remember you can do it anyway with QGIS… great! 🙂
QGIS has a very nice way for handling the python macros at project level, you can define and run the macro when opening, saving or closing a project. In this post I would like share a small and trivial python snippets on how to get alternating layers inside the TOC (Table of Contents) of QGIS by using a python macro in order to switch between different base layers like Bing Map, Google Map, OpenStreetMap.
from PyQt4.QtCore import * from qgis.core import QgsProject, QgsLayerTreeGroup def openProject(): groupName = 'Your group name' def changeVis(nodeLayer, state): if not isinstance(nodeLayer, QgsLayerTreeGroup): childNodes = grp.findLayers() if state == Qt.Checked: for node in childNodes: if node.layerId() != nodeLayer.layerId(): node.setVisible(Qt.Unchecked) global grp root = QgsProject.instance().layerTreeRoot() grp = root.findGroup(groupName) grp.setVisible(Qt.Unchecked) grp.visibilityChanged.connect(changeVis) def saveProject(): pass def closeProject(): grp.visibilityChanged.disconnect()
Here you can find the snippets that I used for alternating visibility to layers. You have to just copy and paste it in “Project properties” dialog under the “Macros” entry and change the group name in the code which you want to apply the macro to.
In your project you have to group the layers between which you want to switch on/off. (make sure you have enabled macros in the QGIS options).
Now the layers inside the group will be mutually unchecked, if one is checked the other ones will be disabled.
That’s all, Cheers!