12. Reading And Storing Settings

Hint

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

1from qgis.core import (
2  Qgis,
3  QgsProject,
4  QgsSettingsEntryEnumFlag,
5  QgsSettingsEntryInteger,
6  QgsSettingsEntryString,
7  QgsVectorLayer
8)

Many times it is useful for a plugin to save some variables so that the user does not have to enter or select them again next time the plugin is run.

We can differentiate between several types of settings:

  • global settings — they are bound to the user at a particular machine. QGIS itself stores a lot of global settings, for example, main window size or default snapping tolerance. They are described in Global settings below.

  • project settings — vary between different projects and therefore they are connected with a project file. Map canvas background color or destination coordinate reference system (CRS) are examples — white background and WGS84 might be suitable for one project, while yellow background and UTM projection are better for another one.

    An example of usage follows.

     1proj = QgsProject.instance()
     2
     3# store values
     4proj.writeEntry("myplugin", "mytext", "hello world")
     5proj.writeEntry("myplugin", "myint", 10)
     6proj.writeEntryDouble("myplugin", "mydouble", 0.01)
     7proj.writeEntryBool("myplugin", "mybool", True)
     8
     9# read values (returns a tuple with the value, and a status boolean
    10# which communicates whether the value retrieved could be converted to
    11# its type, in these cases a string, an integer, a double and a boolean
    12# respectively)
    13
    14mytext, type_conversion_ok = proj.readEntry("myplugin",
    15                                            "mytext",
    16                                            "default text")
    17myint, type_conversion_ok = proj.readNumEntry("myplugin",
    18                                              "myint",
    19                                              123)
    20mydouble, type_conversion_ok = proj.readDoubleEntry("myplugin",
    21                                                    "mydouble",
    22                                                    123)
    23mybool, type_conversion_ok = proj.readBoolEntry("myplugin",
    24                                                "mybool",
    25                                                123)
    

    As you can see, the writeEntry() method is used for many data types (integer, string, list), but several methods exist for reading the setting value back, and the corresponding one has to be selected for each data type.

  • map layer settings — these settings are related to a particular instance of a map layer with a project. They are not connected with underlying data source of a layer, so if you create two map layer instances of one shapefile, they will not share the settings. The settings are stored inside the project file, so if the user opens the project again, the layer-related settings will be there again. The value for a given setting is retrieved using the customProperty() method, and can be set using the setCustomProperty() one.

    1vlayer = QgsVectorLayer()
    2# save a value
    3vlayer.setCustomProperty("mytext", "hello world")
    4
    5# read the value again (returning "default text" if not found)
    6mytext = vlayer.customProperty("mytext", "default text")
    

12.1. Global settings

Global settings are saved in the QGIS/QGIS4.ini file of the active user profile. Each setting is declared once as a settings entry, with its type, its default value and a description, and is placed in the settings tree.

12.1.1. Settings entries

A settings entry is an object describing a single setting: its name, its parent node in the settings tree, its default value, a description and, for some types, the accepted range of values. There is one class per type of value, such as QgsSettingsEntryString or QgsSettingsEntryInteger.

Compared to reading and writing values by their key, settings entries:

  • return values of the right type, without any conversion;

  • define the default value in a single place;

  • reject values outside of the accepted range;

  • are listed, with their description and type, in the Advanced Settings Editor (see Advanced settings), where they can be edited with a widget suited to their type.

12.1.1.1. The settings tree

All the settings entries are organized in a tree, QgsSettingsTree. Each node of the tree is a QgsSettingsTreeNode. QGIS settings live under nodes such as core, gui or digitizing, and plugin settings live under plugins/<plugin_name>.

A settings entry is attached to the tree as soon as it is created: the second argument of its constructor is its parent node. The key of the setting is made of the key of its parent node, followed by the name of the setting.

12.1.1.2. The plugin settings node

Since QGIS 4.2, when a Python plugin is started, QGIS creates a settings node for it and makes it available as the SETTINGS_NODE attribute of the plugin package. The key of this node is plugins/<plugin_name>, where <plugin_name> is the name of the plugin folder. When the plugin is unloaded, QGIS removes the node and the settings entries declared under it. The stored values are kept, and are found again the next time the plugin is loaded.

A plugin which does not declare any settings is not affected: the node only exists in memory, and nothing is written to the settings file until a value is set.

It is good practice to declare all the settings of a plugin in a dedicated module, for example settings.py:

 1# my_plugin/settings.py
 2from qgis.core import QgsSettingsEntryBool, QgsSettingsEntryString
 3
 4from . import SETTINGS_NODE
 5
 6GREETING = QgsSettingsEntryString(
 7    "greeting", SETTINGS_NODE, "Hello", "Message displayed by the plugin"
 8)
 9LOUD = QgsSettingsEntryBool(
10    "loud", SETTINGS_NODE, False, "Display the message in upper case"
11)

The other modules of the plugin import this module and use the settings entries directly:

 1# my_plugin/my_plugin.py
 2from qgis.core import Qgis, QgsMessageLog
 3
 4from . import settings
 5
 6
 7class MyPlugin:
 8    def __init__(self, iface):
 9        self.iface = iface
10
11    def initGui(self):
12        pass
13
14    def unload(self):
15        pass
16
17    def say_hello(self):
18        msg = settings.GREETING.value()
19        if settings.LOUD.value():
20            msg = msg.upper() + "!!!"
21        QgsMessageLog.logMessage(msg, "MyPlugin", Qgis.MessageLevel.Info)
22
23        # write a setting back
24        settings.LOUD.setValue(not settings.LOUD.value())

Warning

QGIS imports the plugin package first and sets SETTINGS_NODE only just before calling classFactory(). The module declaring the settings must therefore not be imported at the top of __init__.py: import the plugin class inside classFactory() instead.

# my_plugin/__init__.py
def classFactory(iface):
    from .my_plugin import MyPlugin
    return MyPlugin(iface)

Note

SETTINGS_NODE requires QGIS 4.2, so set qgisMinimumVersion=4.2 in the metadata of the plugin.

12.1.1.3. Reading and writing values

The snippets below use the SETTINGS_NODE of a plugin. A setting can only be declared once in a node: declaring it a second time raises a QgsSettingsException.

The value of a setting is read with value() and written with setValue(). As long as no value is stored, the default value is returned.

 1MAX_FEATURES = QgsSettingsEntryInteger(
 2    "max-features",
 3    SETTINGS_NODE,
 4    1000,
 5    "Maximum number of features to process",
 6    minValue=1,
 7)
 8
 9print(MAX_FEATURES.key())
10print(MAX_FEATURES.value())  # no value stored yet: the default value
11
12MAX_FEATURES.setValue(500)
13print(MAX_FEATURES.value())
14
15# values outside of the accepted range are rejected
16print(MAX_FEATURES.setValue(0))
17print(MAX_FEATURES.value())
18
19# remove the stored value: the default value applies again
20MAX_FEATURES.remove()
21print(MAX_FEATURES.exists())
22print(MAX_FEATURES.value())
1/plugins/my_plugin/max-features
21000
3500
4False
5500
6False
71000

Settings entries also provide defaultValue() and valueWithDefaultOverride(), which returns the stored value or, if there is none, the given default value.

12.1.1.4. Available types

The following settings entries are available. Their constructor takes the name of the setting, its parent node, the default value, a description and options, followed by the arguments specific to the type.

Class

Type of value

Specific arguments

QgsSettingsEntryBool

bool

QgsSettingsEntryInteger

int

minValue, maxValue

QgsSettingsEntryDouble

float

minValue, maxValue, displayDecimals

QgsSettingsEntryString

str

minLength, maxLength

QgsSettingsEntryStringList

list of str

QgsSettingsEntryColor

QColor

allowAlpha

QgsSettingsEntryVariantMap

dict

QgsSettingsEntryVariant

any value which can be stored in a QVariant

QgsSettingsEntryEnumFlag

a member of an enum or a flag

Enum and flag settings are stored by the name of their member rather than by its integer value, which keeps the settings file readable. Use the SaveEnumFlagAsInt option to store the integer value instead.

1DISTANCE_UNIT = QgsSettingsEntryEnumFlag(
2    "distance-unit",
3    SETTINGS_NODE,
4    Qgis.DistanceUnit.Meters,
5    "Unit used to display distances",
6)
7
8DISTANCE_UNIT.setValue(Qgis.DistanceUnit.Kilometers)
9print(DISTANCE_UNIT.value().name)
Kilometers

The SaveFormerValue option keeps the previous value of the setting each time it changes. The previous value is then returned by formerValue().

12.1.1.5. Organizing settings

To group related settings, create child nodes with createChildNode():

EXPORT_NODE = SETTINGS_NODE.createChildNode("export")
EXPORT_FORMAT = QgsSettingsEntryString("format", EXPORT_NODE, "GPKG")

print(EXPORT_FORMAT.key())
/plugins/my_plugin/export/format

When the same group of settings must be stored for several items, whose names are only known at runtime, use a named list node (QgsSettingsTreeNamedListNode), created with createNamedListNode(). This is for instance the case of the connections to several servers, each with its own URL and user name. The settings declared under a named list node take the name of the item as an additional argument, which is the dynamic part of their key.

 1SERVERS_NODE = SETTINGS_NODE.createNamedListNode("servers")
 2SERVER_URL = QgsSettingsEntryString("url", SERVERS_NODE, "")
 3SERVER_USER = QgsSettingsEntryString("user", SERVERS_NODE, "")
 4
 5SERVER_URL.setValue("https://alpha.example.com", "alpha")
 6SERVER_USER.setValue("jane", "alpha")
 7SERVER_URL.setValue("https://beta.example.com", "beta")
 8
 9print(SERVERS_NODE.items())
10print(SERVER_URL.value("beta"))
11print(SERVER_URL.key("alpha"))
12
13# remove all the settings of an item
14SERVERS_NODE.deleteItem("alpha")
15print(SERVERS_NODE.items())
['alpha', 'beta']
https://beta.example.com
/plugins/my_plugin/servers/items/alpha/url
['beta']

Named list nodes can be nested. The dynamic part of the key is then given as a list of names, from the outermost to the innermost item. Created with the NamedListSelectedItemSetting option, a named list node also stores which of its items is selected, with setSelectedItem() and selectedItem().

12.1.1.6. Conventions

These conventions are the ones followed by QGIS itself (see the QGIS coding standards):

  • declare each setting once, at the module level, and use it from everywhere else;

  • use kebab-case for the names of settings and nodes, for example max-features rather than maxFeatures or max_features;

  • give each setting a description, which is displayed in the Advanced Settings Editor;

  • group related settings in child nodes, rather than putting / in the names of the settings.

A plugin which used to store its values with QgsSettings can move them to the new keys with copyValueFromKey(). The value is only copied if the old key exists and the new one does not, so this can safely be run each time the plugin is loaded:

GREETING = QgsSettingsEntryString("greeting", SETTINGS_NODE, "Hello")
# move the value stored by an older version of the plugin, if any
GREETING.copyValueFromKey("myplugin/greeting", removeSettingAtKey=True)