Turning on/off ALL selected layers in QGIS

In the Layer pannel, there is an icon in form of an eye : Manage Map Themes (documentation) :

qgis layer panel

By clicking on it, you can see the option for display / mask the selected layers.

You can also go to the Settings menu > Shortcuts, find these options (one for display selected, one for mask selected) and affect the shortcut you want.


PyQGIS code :

Copy and execute the following code in the Python console and now, you can display / mask selected layers with the Ctrl + Space shortcut.

The key sequence can be changed with the Qt.Key codes.

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QShortcut
from qgis.core import QgsProject
from qgis.utils import iface


def display_mask_selected_layers():
    ltr = QgsProject.instance().layerTreeRoot()
    layers = iface.layerTreeView().selectedLayers()
    switch = False

    for i, layer in enumerate(layers):
        node = ltr.findLayer(layer.id())
        if node:
            if i == 0:
                switch = not node.itemVisibilityChecked()

            node.setItemVisibilityChecked(switch)


shortcut = QShortcut(
    QKeySequence(
        # set the key sequence, here Ctrl + Space
        Qt.ControlModifier + Qt.Key_Space
    ),
    iface.mainWindow()
)
shortcut.setContext(Qt.ApplicationShortcut)
shortcut.activated.connect(display_mask_selected_layers)

Make the file startup.py with the code above and copy it into (source) :

  • for Linux : /home/<session_name>/.local/share/QGIS/QGIS3
  • for Windows (assuming C: is the system drive) : C:\Users\<session_name>\AppData\Roaming\QGIS\QGIS3\startup.py
  • for MacOS : Library/Application Support/QGIS/QGIS3

In QGIS 3.14+, you can now toggle the visibility of the currently selected layer(s) or group(s) with "Space" button.

enter image description here

Tags:

Layers

Qgis 3