16.2. Code Snippets


The code snippets on this page need the following imports if you’re outside the pyqgis console:

 1from qgis.core import (
 2    QgsProject,
 3    QgsApplication,
 6from qgis.gui import (
 7    QgsGui,
 8    QgsOptionsWidgetFactory,
 9    QgsOptionsPageWidget
12from qgis.PyQt.QtCore import Qt
13from qgis.PyQt.QtWidgets import QMessageBox, QAction, QHBoxLayout
14from qgis.PyQt.QtGui import QIcon

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)

To unload() add


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")

It is also possible to allow users to customize key shortcuts for the provided actions. This is done by adding:

1# in the initGui() function
4# and in the unload() function

16.2.2. How to reuse QGIS icons

Because they are well-known and convey a clear message to the users, you may want sometimes to reuse QGIS icons in your plugin instead of drawing and setting a new one. Use the getThemeIcon() method.

For example, to reuse the fileOpen mActionFileOpen.svg icon available in the QGIS code repository:

1# e.g. somewhere in the initGui
2self.file_open_action = QAction(
3    QgsApplication.getThemeIcon("/mActionFileOpen.svg"),
4    self.tr("Select a File..."),
5    self.iface.mainWindow()
7self.iface.addPluginToMenu("MyPlugin", self.file_open_action)

iconPath() is another method to call QGIS icons. Find examples of calls to theme icons at QGIS embedded images - Cheatsheet.

16.2.3. 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):
 3    def __init__(self):
 4        super().__init__()
 6    def icon(self):
 7        return QIcon('icons/my_plugin_icon.svg')
 9    def createWidget(self, parent):
10        return ConfigOptionsPage(parent)
13class ConfigOptionsPage(QgsOptionsPageWidget):
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
 5class MyPlugin:
 6    """QGIS Plugin Implementation."""
 8    def __init__(self, iface):
 9        """Constructor.
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
20    def initGui(self):
21        self.options_factory = MyPluginOptionsFactory()
22        self.options_factory.setTitle(self.tr('My Plugin'))
23        iface.registerOptionsWidgetFactory(self.options_factory)
25    def unload(self):
26        iface.unregisterOptionsWidgetFactory(self.options_factory)


Add custom tabs to 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.