4

Under Settings>Options>Layout>Layout Paths we can define Path(s) to search for extra print templates like shown here:

enter image description here

I intend to deploy an organization-wide standard path for print templates using PyQGIS in a startup-script but struggle in finding a method that does what I desire.

I cannot find something related in the QgsSettings(), but I found a method

QgsApplication.instance().layoutTemplatePaths()

returning a list of the currently defined print template paths, but no equivalent method setLayoutTemplatePaths().

How may I set these print template paths using PyQGIS?

1 Answer 1

5

The values are in the QGIS3.ini and under QGIS, in the properties > Advanced tab > core > Layout > searchPathsForTemplates.

I modify the values with the following code :

new_template_dir = "/home/me/my_custom_template_dir"
app = QgsApplication.instance()
params = QgsSettings(
    app.qgisSettingsDirPath() + "QGIS/QGIS3.ini", QSettings.IniFormat
)
params.beginGroup("/core/Layout")
# retrieve the current directories
existing_dir = params.value("searchPathsForTemplates")
# append the new one in the list
if existing_dir is None:
    existing_dir = [new_template_dir]
elif isinstance(existing_dir, str):
    if new_template_dir != existing_dir:
        existing_dir = [existing_dir, new_template_dir]
    else:
        existing_dir = [existing_dir]
elif isintance(existing_dir, list):
    if new_template_dir not in existing_dir:
        existing_dir.append(new_template_dir)

# setting the new list
params.setValue("searchPathsForTemplates", existing_dir)

The code can be improved by verifying the new_template_dir exists for example but for me, it works.

5
  • It should be noted, that in cases of exactly one template path existing_dir will be a string, not a one-element-list as one might expect which throws a traceback in the ...append() line Commented Dec 2, 2019 at 8:13
  • And furthermore, if no template path is specified, we'll get an empty list. A bit weird me thinks. Commented Dec 2, 2019 at 8:18
  • I've improved the code. Commented Dec 2, 2019 at 8:23
  • This is a bit like code golf, but IMHO you can skip the test for existing_dir == "" because I think this never happens (correct me if I'm wrong, it's monday morning...) and replace the test for list with simply else ;-) Commented Dec 2, 2019 at 8:32
  • I replace it with is None test because in my QGIS, it was None, and I prefer to leave the elif``with tests that readable and avoid else` like an except without error type. But it's monday morning for me too ! Commented Dec 2, 2019 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.