1

I create a new print layout using PyQgis and then I open it in the layout designer. Everything seems ok till I try to refresh the page or update the map extent, then map disappears.

project = QgsProject.instance()
lmg = QgsProject.instance().layoutManager()
l = QgsPrintLayout(project)
l.initializeDefaults()
l.setUnits(QgsUnitTypes.LayoutMillimeters)
lmg.clear()
lmg.addLayout(l)
page = l.pageCollection().pages()[0]  

lm = 20         # left margin
tm = 32         # upper margin

w, h = 900, 600 #width and height
page.setPageSize(QgsLayoutSize(1189, 841))  
theMap = QgsLayoutItemMap(l)
theMap.updateBoundingRect()
theMap.setRect(QRectF(lm,tm, w, h)) 
theMap.setPos(lm,tm)
theMap.setFrameEnabled(True)
theMap.updateBoundingRect()
theMap.setLayers(project.mapThemeCollection().masterVisibleLayers())   
theMap.setExtent(QgsRectangle(363600.0, 376800.0, 364500.0 ,377400.0))
theMap.attemptSetSceneRect(QRectF(lm,tm, w, h))
l.addItem(theMap)
l.updateBounds()

iface.openLayoutDesigner(l)

enter image description hereenter image description here

1

I found that the problem was with the map size 900x600 (I don't know why?) , so I solved it by initializing the map with lower size (half size in the example)

theMap.setRect(QRectF(lm,tm, 450, 300)) 

Then I resized it the disired dimension using attemptSetSceneRect method:

theMap.attemptSetSceneRect(QRectF(lm,tm, w, h))
  • Thank you for following. I've tried under QGIS 3.6.1 Ubuntu, I just changed the extent coordinates and everything went well without your workaround. – J. Monticolo May 23 at 12:52
  • Yes it works for me too when changing the extent, but I needed to print the given one – Youssef May 23 at 13:30

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.