[QGIS-Developer] Difference in layer order between map and exported image

afernandez at odyhpc.com afernandez at odyhpc.com
Sun May 25 10:05:54 PDT 2025


Hello,
I'm reordering the map layers using
     my_instance = QgsProject.instance()
     my_tree = my_instance.layerTreeRoot()
      ...
     my_tree.setCustomLayerOrder(my_layers)
     my_tree.setHasCustomLayerOrder(True)
This works smoothly and the map canvas looks as targeted. However, the 
problem arises when calling a function to export the image. The lines to 
accomplish this task read:
def my_export_function(...):
     my_project = QgsProject.instance()
     manager = my_project.layoutManager()
     layout = QgsPrintLayout(my_project)
     layout.initializeDefaults()
     ... (lines to set up canvas size and others)
     exporter = QgsLayoutExporter(layout)
     canvas_settings = exporter.ImageExportSettings()
     exporter.exportToImage(png_name, settings=canvas_settings)
When the image is exported for the first time, It completely ignores the 
order of the layers previously set up with 'my_layers'. The perplexing 
thing is that when the function is called to export the image for a 
second time (without doing anything else), the new exported image 
follows the new layer order. I've been going over this issue for the 
last 2 weeks but cannot figure out what controls the layer order of the 
exported image or how to fix the issue.
Thanks.


More information about the QGIS-Developer mailing list