4

I want to create an atlas composer map using PyQGIS 3.

How can I take dynamic path by field from atlas layer?

enter image description here enter image description here

In PyQGIS 3 I need some like this :

pict = QgsLayoutItemPicture(layout)
pict.setPicturePath(myAtlas['pict'])
pict.setFrameEnabled(True)

where myAtlas is my layer and pict is my field with paths.

1 Answer 1

6

For the expression, you should use the following

if(
  file_exists(attribute(@atlas_feature, 'pict')),
  attribute(@atlas_feature, 'pict'),
  '/tmp/fallback.png'
)

For manipulating expressions, you should use

from qgis.core import QgsProject, QgsLayoutItemPicture

project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName('atlas')

# By default, when you create any component in the layout component, no Item ID, so set it before
item = layout.itemById('theidoftheQgsLayoutItemPicture')
your_atlas_field = 'pict'
expression = "if(\n  file_exists(attribute(@atlas_feature, '{field}')),\n  attribute(@atlas_feature, '{field}'),\n  '/tmp/fallback.png'\n)".format(field=your_atlas_field)
item.dataDefinedProperties().property(QgsLayoutObject.PictureSource).setExpressionString(expression)
item.dataDefinedProperties().property(QgsLayoutObject.PictureSource).setActive(True)
0

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.