1

Does anyone know any shortcut to display / hide the layers as per the order? For example, F1 displays and hides layer 1, F2 displays and hides layer 2. I found the shortcut to hide all the layers and hide the selected layer, but for what I want it does not work, because I need to edit layer 1 (shp) and toggle between displaying and hiding layer 2 (raster). QGIS 2.18

0

Not exactly what you're asking for but close. The following code when run from the QGIS 2.x Python console (tested on 2.16.0) will let you to choose a layer then toggle its visibility.

  • Selecting a layer then pressing Alt Z will choose it for toggling.

  • Pressing Z will toggle the chosen layer's visibility regardless of which layer is currently active.

Here's the code:

from PyQt4.QtGui import QShortcut, QKeySequence
from PyQt4.QtCore import Qt

root = QgsProject.instance().layerTreeRoot()
currentToggleNode = root.findLayer(iface.activeLayer().id())

def setToggleLayer():
  currentToggleNode = root.findLayer(iface.activeLayer().id())

def toggleLayer():
  new_state = Qt.Checked if currentToggleNode.isVisible() == Qt.Unchecked else Qt.Unchecked
  currentToggleNode.setVisible(new_state)

shortcutSetToggleLayer = QShortcut(QKeySequence(Qt.AltModifier + Qt.Key_Z), iface.mainWindow())
shortcutSetToggleLayer.setContext(Qt.ApplicationShortcut)
shortcutSetToggleLayer.activated.connect(setToggleLayer)

shortcutToggleLayer = QShortcut(QKeySequence(Qt.Key_Z), iface.mainWindow())
shortcutToggleLayer.setContext(Qt.ApplicationShortcut)
shortcutToggleLayer.activated.connect(toggleLayer)

You'll need to run the above code from the Python console once each time you start QGIS (you can save it in a script file to avoid retyping; see the QGIS docs for details). If you get any error messages you'll need to restart QGIS before fixing the problematic code since Python state is pretty persistent within a QGIS session.

Known bugs:

  • Will probably break if toggling (Z) is used before a toggle layer has been selected (with Alt Z)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.