5

When I select few layers in the QGIS 3 Layers Panel and press Space - only one of the selected layers is turned off/on. I want to turn them all. How to do that?

few

10

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
  • Thanks! So I need two shortcut keys to perform this action? Can't assing on and off actions to one key. Here is feature request for this: github.com/qgis/QGIS/issues/33874 – Mr. Che Jan 17 at 9:40
  • I've added Python code with a unique shortcut binding. – J. Monticolo Jan 17 at 10:18
  • I am trying to paste this code as startup marco but it fails because of incorrect imports. Some of them I know (i.e. from qgis.utils import iface), but cant find the other (QShortcut, Qt, etc). – Mr. Che Jan 17 at 12:34
  • @Mr.Che: added in my answer. – J. Monticolo Jan 17 at 12:40
  • To run this script when starting QGIS, put it in "C:\Users\USERNAME\AppData\Roaming\QGIS\QGIS3\startup.py" – Mr. Che Jan 20 at 4:43

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.