stratified_packager.toolbelt.settings
QGIS-specific persistence proxies: typed settings, project entries, variables, layer properties.
This module wraps the disparate QGIS persistence APIs documented in the PyQGIS Developer Cookbook (Reading and Storing Settings) behind a small set of Pythonic objects that read and write values while converting to and from the appropriate Python types:
Proxy |
Backing QGIS API |
|---|---|
|
|
the above plus typed |
|
|
|
|
|
|
Two complementary access styles are offered, mirroring how
QgsSettingsEntry* sits over a flat store:
Dict-like — every proxy is a
MutableMappingkeyed by string, so arbitrary dynamic keys work out of the box:gs = SettingsProxy() gs["ui/theme"] # raw stored value gs.get("max_threads", 4, cast=int) # with type and default
Typed descriptors —
PluginSettingsBasesubclasses declare known keys as class attributes whoseSettingdescriptors read and write typedQgsSettingsEntry*objects registered under the plugin’s node in the global settings tree:class MySettings(PluginSettingsBase): _PLUGIN_NAME = "my_plugin" debug_mode = BoolSetting(default=False) s = MySettings() s.debug_mode # -> bool s.debug_mode = True # persisted
The proxies build on the QGIS-free mapping_proxy: they subclass its
MappingProxy and read and write through its conversion registry
(to_storage() / from_storage()). That registry
covers the stdlib types; this module registers the QGIS-only QColor
converter at import so ColorSetting and cast=QColor round-trip.
Warning
Every proxy here touches main-thread QGIS objects (QgsProject,
QgsMapLayer), so they must only be used on the GUI thread.
qgis.core.QgsSettings is the sole exception (it is thread-safe), but
the proxies make no special accommodation for off-thread use.
Classes
|
A |
|
A |
|
A |
|
An |
|
An |
|
Dict-like proxy over a layer's custom properties. |
|
Dict-like proxy over a layer's expression variables. |
|
Plugin-agnostic base for a plugin's typed settings schema, scoped under |
|
Dict-like proxy over a project's custom entries ( |
|
Dict-like proxy over a project's expression variables. |
|
Descriptor mapping a class attribute to a typed |
|
Dict-like proxy over |
|
A |
|
A |
|
A |
|
A free-form setting backed by |
- class stratified_packager.toolbelt.settings.BoolSetting(default, description='', *, key=None)[source]
A
boolsetting backed byQgsSettingsEntryBool.
- class stratified_packager.toolbelt.settings.ColorSetting(default, description='', *, key=None)[source]
A
QColorsetting.Backed by
QgsSettingsEntryColor.
- class stratified_packager.toolbelt.settings.DoubleSetting(default, description='', *, key=None)[source]
A
floatsetting backed byQgsSettingsEntryDouble.
- class stratified_packager.toolbelt.settings.EnumSetting(enum_type, default, description='', *, key=None)[source]
An
enum.Enumsetting persisted by its membervalue.The backing
QgsSettingsEntry*is chosen from the type of the default member’svalue(bool/int/float/str, falling back toQgsSettingsEntryVariant). Reading reconstructs the member viaenum_type(stored_value), which also handlesenum.IntFlagcombinations. This sidesteps the inconsistent return typing ofQgsSettingsEntryEnumFlagwhile still persisting through a typed entry.- Parameters:
- _build_entry(plugin_name)[source]
Construct a typed entry storing the member value (see the class docstring).
- Parameters:
plugin_name (
str) – Plugin name inserted into the entry key.- Return type:
- Returns:
A backing entry whose value type matches the enum’s values.
- _decode(entry)[source]
Rebuild the enum member from the stored value.
- Parameters:
entry (
QgsSettingsEntryVariant) – The backing entry to read.- Return type:
- Returns:
The reconstructed enum member.
- class stratified_packager.toolbelt.settings.IntSetting(default, description='', *, key=None)[source]
An
intsetting backed byQgsSettingsEntryInteger.
- class stratified_packager.toolbelt.settings.LayerCustomProperties(layer)[source]
Dict-like proxy over a layer’s custom properties.
Wraps
qgis.core.QgsMapLayer.customProperty()/setCustomProperty()— arbitrary key/value pairs persisted with the layer in the project file.- Parameters:
layer (
QgsMapLayer)
- __init__(layer)[source]
Initialize the proxy.
- Parameters:
layer (
QgsMapLayer) – The layer whose custom properties are proxied.
- _abc_impl = <_abc._abc_data object>
- class stratified_packager.toolbelt.settings.LayerVariables(layer)[source]
Dict-like proxy over a layer’s expression variables.
Wraps
qgis.core.QgsExpressionContextUtils’ layer scope — the@-variables shown under Layer Properties → Variables.As with
ProjectVariables, iteration and membership reflect the full layer scope (including built-ins such aslayer_name/layer_id). QGIS exposes noremoveLayerVariable, so deletion rewrites the layer’s user-defined variables without the removed key viaqgis.core.QgsExpressionContextUtils.setLayerVariables(); deleting a name that exists only as a built-in therefore has no effect.- Parameters:
layer (
QgsMapLayer)
- __init__(layer)[source]
Initialize the proxy.
- Parameters:
layer (
QgsMapLayer) – The layer whose variables are proxied.
- _scope()[source]
Return a fresh layer expression scope.
- Return type:
- Returns:
The layer
QgsExpressionContextScope.- Raises:
RuntimeError – If QGIS returns no layer scope.
- _VARIABLE_NAMES_PROPERTY: ClassVar[str] = 'variableNames'
Custom-property key under which QGIS stores user-defined variable names.
- _VARIABLE_VALUES_PROPERTY: ClassVar[str] = 'variableValues'
Custom-property key under which QGIS stores user-defined variable values.
- _abc_impl = <_abc._abc_data object>
- _layer: qgis.core.QgsMapLayer
- class stratified_packager.toolbelt.settings.PluginSettingsBase(*, settings=None)[source]
Plugin-agnostic base for a plugin’s typed settings schema, scoped under
plugins/<name>.Concrete subclasses set a non-empty
_PLUGIN_NAMEand declare their known keys as typedSettingdescriptors while remaining a full dict-likeSettingsProxyfor any additional keys. Because the scope matches the descriptors’ entry keys,self.<key>andself["<key>"]address the same stored value. Everything is derived from_PLUGIN_NAME, so this class carries no dependency on any particular plugin. The name is enforced at class-creation time (see__init_subclass__); an intermediate base that leaves it intentionally unset must opt out withclass Mixin(PluginSettingsBase, abstract=True).- Parameters:
settings (QgsSettings | None)
- classmethod teardown()[source]
Unregister the plugin’s settings-tree node and drop cached descriptor entries.
Call this from the plugin’s
unload()so a subsequent reload can re-register the sameSettingentries cleanly. Safe to call when nothing has been registered.- Return type:
- __init__(*, settings=None)[source]
Initialize the proxy scoped to the plugin’s settings node.
- Parameters:
settings (QgsSettings | None) – Existing
QgsSettingsto use; a fresh one is created when omitted.
- reset_defaults()[source]
Remove every declared
Setting’s stored value, restoring its default.- Return type:
- _PLUGIN_NAME: ClassVar[str]
Plugin name (tree node and scope); a concrete subclass MUST set a non-empty value.
- _abc_impl = <_abc._abc_data object>
- class stratified_packager.toolbelt.settings.ProjectEntries(scope, *, project=None)[source]
Dict-like proxy over a project’s custom entries (
qgis.core.QgsProject.writeEntry()).Entries are persisted in the
.qgs/.qgzfile under a caller-supplied scope (group). They are not exposed as expression variables — useProjectVariablesfor those.QGIS reads project entries through type-specific methods, so for typed reads use
get()withcast=; plain[]access returns the value as a string. Writes dispatch on the Python type to the matchingwriteEntry*method —writeEntryBool()/writeEntryDouble()forbool/float, andwriteEntry()for everything else — so each value round-trips through its correspondingread*Entry(e.g. read a float back withcast=float). Iteration yields the immediate child entry keys of the scope; nested keys are reached with a proxy scoped one level deeper.- Parameters:
scope (str)
project (QgsProject | None)
- __init__(scope, *, project=None)[source]
Initialize the proxy.
- Parameters:
scope (str) – Entry scope (group) name (e.g. the plugin slug).
project (QgsProject | None) – Project to read/write; defaults to
qgis.core.QgsProject.instance().
- _raw_del(key)[source]
Remove key from the project scope.
- Parameters:
key (
str) – The entry key.- Raises:
RuntimeError – If
QgsProjectreports the removal failed.- Return type:
- _raw_set(key, value)[source]
Write value at key, dispatching on the storable type.
- Parameters:
key (
str) – The entry key.value (
object) – The storable value already passed throughto_storage().
- Raises:
RuntimeError – If
QgsProjectreports the write failed.- Return type:
- _typed_get(key, cast)[source]
Read key with the
QgsProjectmethod matching cast.bool,int,floatandlistroute toreadBoolEntry(),readNumEntry(),readDoubleEntry()andreadListEntry()respectively; other casts read the string entry and convert viafrom_storage().
- _abc_impl = <_abc._abc_data object>
- _project: qgis.core.QgsProject
- class stratified_packager.toolbelt.settings.ProjectVariables(*, project=None)[source]
Dict-like proxy over a project’s expression variables.
Wraps
qgis.core.QgsExpressionContextUtils’ project scope — the@-variables shown under Project Properties → Variables. Assignment creates or replaces a user-defined variable; deletion removes one.Iteration and membership reflect the full project scope, which also includes QGIS’ built-in project variables (
project_path,project_title, …). Those built-ins are read-only: deleting a name that exists only as a built-in has no effect.- Parameters:
project (QgsProject | None)
- __init__(*, project=None)[source]
Initialize the proxy.
- Parameters:
project (QgsProject | None) – Project to read/write; defaults to
qgis.core.QgsProject.instance().
- _scope()[source]
Return a fresh project expression scope.
- Return type:
- Returns:
The project
QgsExpressionContextScope.- Raises:
RuntimeError – If QGIS returns no project scope.
- _abc_impl = <_abc._abc_data object>
- _project: qgis.core.QgsProject
- class stratified_packager.toolbelt.settings.Setting(default, description='', *, key=None)[source]
Descriptor mapping a class attribute to a typed
QgsSettingsEntry*.Declare instances as class attributes of a
PluginSettingsBasesubclass. On first access, the descriptor lazily constructs its backing entry using the plugin constructor of the relevantQgsSettingsEntry*class — keyed by the owning proxy’sPluginSettingsBase._PLUGIN_NAME— so the value is persisted atplugins/<plugin-name>/<key>and appears in the QGIS settings tree. That key coincides with the one aSettingsProxyprefixed withplugins/<plugin-name>produces, so descriptor access and dict access address the same stored value.Subclasses set
_ENTRY_CLASSto the concrete entry type; onlyEnumSettingneeds to override the value-marshalling hooks.- _build_entry(plugin_name)[source]
Construct the backing entry under plugin_name’s settings node.
The concrete entry is built from
_ENTRY_CLASSand viewed as aQgsSettingsEntryVariantso itsvalue/setValuemethods are visible to type checkers (the abstract base lacks them).- Parameters:
plugin_name (
str) – Plugin name inserted into the entry key.- Return type:
- Returns:
The backing entry, viewed as a variant entry.
- _decode(entry)[source]
Marshal the entry’s stored value into
T.- Parameters:
entry (
QgsSettingsEntryVariant) – The backing entry to read.- Return type:
TypeVar(T)- Returns:
The typed value.
- _entry(owner)[source]
Return the backing entry for owner, building and caching it on first use.
- Parameters:
owner (
type[PluginSettingsBase]) – ThePluginSettingsBasesubclass owning the descriptor.- Return type:
- Returns:
The cached backing entry.
- _forget()[source]
Drop cached entries so they are rebuilt after a settings-tree teardown.
- Return type:
- reset(owner)[source]
Remove the stored value so the default applies again.
- Parameters:
owner (
type[PluginSettingsBase]) – The owningPluginSettingsBasesubclass.- Return type:
- _ENTRY_CLASS: ClassVar[type[QgsSettingsEntryBase]]
Concrete
QgsSettingsEntry*class backing this descriptor.
- _default: T
- _entries: dict[type, QgsSettingsEntryVariant]
- class stratified_packager.toolbelt.settings.SettingsProxy(prefix='', *, settings=None)[source]
Dict-like proxy over
qgis.core.QgsSettings, optionally scoped to a prefix.Keys are joined to prefix with
/; an empty prefix (the default) addresses the raw global namespace, soSettingsProxy()["ui/theme"]reads the same key the QGIS options dialog writes.For typed reads prefer
get()withcast=— it routes the native types (str,int,float,bool,list) throughqgis.core.QgsSettings.value()’s own coercion (which correctly turns the string"true"back intoTrue) and uses the converter registry for the rest. Plain[]access returns the raw stored value without coercion.- Parameters:
prefix (str)
settings (QgsSettings | None)
- __init__(prefix='', *, settings=None)[source]
Initialize the proxy.
- Parameters:
prefix (str) – Key prefix; surrounding slashes are stripped.
settings (QgsSettings | None) – Existing
QgsSettingsto use; a fresh one is created when omitted.
- _full_key(key)[source]
Join key to the configured prefix.
- Parameters:
key (
str) – The relative key.- Return type:
- Returns:
The fully qualified
QgsSettingskey.
- _raw_get(key)[source]
Read key from
QgsSettings.
- _typed_get(key, cast)[source]
Read key, coercing native types through
qgis.core.QgsSettings.value().
- _NATIVE_TYPES: ClassVar[tuple[type, ...]] = (<class 'str'>, <class 'int'>, <class 'float'>, <class 'bool'>, <class 'list'>)
Types
qgis.core.QgsSettings.value()can coerce directly via itstype=argument.
- _abc_impl = <_abc._abc_data object>
- _settings: qgis.core.QgsSettings
- class stratified_packager.toolbelt.settings.StringListSetting(default, description='', *, key=None)[source]
A
list[str]setting backed byQgsSettingsEntryStringList.
- class stratified_packager.toolbelt.settings.StringSetting(default, description='', *, key=None)[source]
A
strsetting backed byQgsSettingsEntryString.
- class stratified_packager.toolbelt.settings.VariantMapSetting(default, description='', *, key=None)[source]
A
dict[str, Any]setting backed byQgsSettingsEntryVariantMap.Values round-trip type-preservingly (nested scalars and string lists keep their Python types). Like every descriptor this is read-replace: mutating the returned dict in place does not persist; reassign the whole value, e.g.
proxy.conf = proxy.conf | {"key": value}.
- class stratified_packager.toolbelt.settings.VariantSetting(default, description='', *, key=None)[source]
A free-form setting backed by
QgsSettingsEntryVariant.
- stratified_packager.toolbelt.settings._resolve_project(project)[source]
Return project, falling back to the singleton
qgis.core.QgsProject.instance().- Parameters:
project (QgsProject | None) – An explicit project, or
Noneto use the singleton.- Return type:
QgsProject
- Returns:
A non-
NoneQgsProject.- Raises:
RuntimeError – If no project is available.