16.2. Code Snippets

This section features code snippets to facilitate plugin development.

16.2.1. How to call a method by a key shortcut

In the plug-in add to the initGui()

self.key_action = QAction("Test Plugin", self.iface.mainWindow())
self.iface.registerMainWindowAction(self.key_action, "Ctrl+I")  # action triggered by Ctrl+I
self.iface.addPluginToMenu("&Test plugins", self.key_action)
self.key_action.triggered.connect(self.key_action_triggered)

To unload() add

self.iface.unregisterMainWindowAction(self.key_action)

The method that is called when CTRL+I is pressed

def key_action_triggered(self):
  QMessageBox.information(self.iface.mainWindow(),"Ok", "You pressed Ctrl+I")

16.2.2. How to toggle Layers

There is an API to access layers in the legend. Here is an example that toggles the visibility of the active layer

root = QgsProject.instance().layerTreeRoot()
node = root.findLayer(iface.activeLayer().id())
new_state = Qt.Checked if node.isVisible() == Qt.Unchecked else Qt.Unchecked
node.setItemVisibilityChecked(new_state)

16.2.3. How to access attribute table of selected features

 1def change_value(value):
 2    """Change the value in the second column for all selected features.
 3
 4    :param value: The new value.
 5    """
 6    layer = iface.activeLayer()
 7    if layer:
 8        count_selected = layer.selectedFeatureCount()
 9        if count_selected > 0:
10            layer.startEditing()
11            id_features = layer.selectedFeatureIds()
12            for i in id_features:
13                layer.changeAttributeValue(i, 1, value) # 1 being the second column
14            layer.commitChanges()
15        else:
16            iface.messageBar().pushCritical("Error",
17                "Please select at least one feature from current layer")
18    else:
19        iface.messageBar().pushCritical("Error", "Please select a layer")
20
21# The method requires one parameter (the new value for the second
22# field of the selected feature(s)) and can be called by
23change_value(50)

16.2.4. Interface for plugin in the options dialog

You can add a custom plugin options tab to Settings ► Options. This is preferable over adding a specific main menu entry for your plugin’s options, as it keeps all of the QGIS application settings and plugin settings in a single place which is easy for users to discover and navigate.

The following snippet will just add a new blank tab for the plugin’s settings, ready for you to populate with all the options and settings specific to your plugin. You can split the following classes into different files. In this example, we are adding two classes into the main mainPlugin.py file.

 1class MyPluginOptionsFactory(QgsOptionsWidgetFactory):
 2
 3    def __init__(self):
 4        super().__init__()
 5
 6    def icon(self):
 7        return QIcon('icons/my_plugin_icon.svg')
 8
 9    def createWidget(self, parent):
10        return ConfigOptionsPage(parent)
11
12
13class ConfigOptionsPage(QgsOptionsPageWidget):
14
15    def __init__(self, parent):
16        super().__init__(parent)
17        layout = QHBoxLayout()
18        layout.setContentsMargins(0, 0, 0, 0)
19        self.setLayout(layout)

Finally we are adding the imports and modifying the __init__ function:

 1from qgis.PyQt.QtWidgets import QHBoxLayout
 2from qgis.gui import QgsOptionsWidgetFactory, QgsOptionsPageWidget
 3
 4
 5class MyPlugin:
 6    """QGIS Plugin Implementation."""
 7
 8    def __init__(self, iface):
 9        """Constructor.
10
11        :param iface: An interface instance that will be passed to this class
12            which provides the hook by which you can manipulate the QGIS
13            application at run time.
14        :type iface: QgsInterface
15        """
16        # Save reference to the QGIS interface
17        self.iface = iface
18
19
20    def initGui(self):
21        self.options_factory = MyPluginOptionsFactory()
22        self.options_factory.setTitle(self.tr('My Plugin'))
23        iface.registerOptionsWidgetFactory(self.options_factory)
24
25    def unload(self):
26        iface.unregisterOptionsWidgetFactory(self.options_factory)

Tip

Add custom tabs to a vector layer properties dialog

You can apply a similar logic to add the plugin custom option to the layer properties dialog using the classes QgsMapLayerConfigWidgetFactory and QgsMapLayerConfigWidget.