Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Created August 13, 2020 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasG77/d15771bb30c231166701cf31788f8a6b to your computer and use it in GitHub Desktop.
Save ThomasG77/d15771bb30c231166701cf31788f8a6b to your computer and use it in GitHub Desktop.
canvas = iface.mapCanvas()
project = QgsProject.instance()
#get a reference to the layout manager
manager = project.layoutManager()
#make a new print layout object
layout = QgsPrintLayout(project)
#needs to call this according to API documentaiton
layout.initializeDefaults()
#cosmetic
layout.setName('console')
#add layout to manager
manager.addLayout(layout)
#create a map item to add
itemMap = QgsLayoutItemMap.create(layout)
#using ndawson's answer below, do this before setting extent
itemMap.attemptResize(QgsLayoutSize(6,4, QgsUnitTypes.LayoutInches))
#set an extent
itemMap.setExtent(canvas.extent())
#add the map to the layout
layout.addLayoutItem(itemMap)
legend = QgsLayoutItemLegend(layout)
legend.setLinkedMap(itemMap)
layout.addLayoutItem(legend)
iface.openLayoutDesigner(layout)
# Copy above only and run
# Then after run in a second time
print(legend.sizeWithUnits(), legend.pagePositionWithUnits())
legend.setReferencePoint(QgsLayoutItem.LowerLeft)
print(legend.sizeWithUnits(), legend.pagePositionWithUnits())
legend.attemptMove(QgsLayoutPoint(100, 200), useReferencePoint=True)
print(legend.sizeWithUnits(), legend.pagePositionWithUnits())
# Above second part not working if run in one time
# Tried to use signal layoutDesignerOpened
# https://qgis.org/api/classQgisInterface.html#ad48fc0421d29316ee36fa84870ee0810
# but not working better...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment