12

In my layout, the legend is placed between other elements. The scale bar is located above the legend and an overview map below it. You can see it in the screenshot below. The legend is expanded or reduced according to the map elements (red arrows). However, the following element (overview map) is static and does not follow the lower limit of the legend and is overrun.

Is it possible, to place elements dynamically according to the position and size of other elements?

enter image description here

1
  • 5
    This is currently not possible in QGIS using the expressions framework, because this would be prone to creating circular dependencies and there's no resolution mechanism for this yet. See this comment by one of QGIS' main developers. You might be able to implement something using some Python scripting though.
    – Jake
    Nov 1, 2020 at 18:48

1 Answer 1

5
+50

A solution using PyQGIS would be like this:

project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName("LAYOUT") # change layout name
legend = layout.itemById("LEGEND")      # change legend name
overview = layout.itemById("OVERVIEW")  # change overview name
interval = 5 # set interval

def legend_changed():
    p = legend.pagePositionWithUnits() # get legend position
    s = legend.sizeWithUnits()         # get legend size
    s_o = overview.sizeWithUnits()     # get overview size
    
    # new position for overview
    overview_new_pos = QgsLayoutPoint(p.x(), p.y() + s.height() + interval)
    # new size for overview
    overview_new_size = QgsLayoutSize(s.width(), s_o.height())
    
    # change position and size of overview
    overview.attemptMove(overview_new_pos)
    overview.attemptResize(overview_new_size)
    
    layout.refresh()
    layout.updateBounds()
    
legend.sizePositionChanged.connect(legend_changed)

enter image description here

3
  • Great! But where do I have to place the code?
    – MartinMap
    Nov 8, 2020 at 16:04
  • Place to QGIS Python Editor and run. This is not permanent, you should run at every opening QGIS unfortunately. Nov 8, 2020 at 16:32
  • ...or I could place it as project macro!
    – MartinMap
    Nov 8, 2020 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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