2

I have made manually one layout in QGIS 3.10, I access it using PyQGIS and I want to add a new QgsLayoutItemMap. I'm unable to set scale correctly. Does I miss a step? Is it a bug? Are you able to reproduce?


layout1 = QgsProject.instance().layoutManager().layouts()[0]

qgsLayoutItemMap2 = QgsLayoutItemMap(layout1)
qgsLayoutItemMap2.setId('myNewId')
qgsLayoutItemMap2.attemptSetSceneRect(QRectF(10, 10, 180, 180))
qgsLayoutItemMap2.setFrameEnabled(True)
qgsLayoutItemMap2.setFrameStrokeColor(QColor(255, 0, 0))
layout1.addItem(qgsLayoutItemMap2)

print(qgsLayoutItemMap2.scale()) # Return 0.0
qgsLayoutItemMap2.setScale(40000.0)
print(qgsLayoutItemMap2.scale()) # Return nan

The second return e.g nan after setting scale seems anormal. Any clue? I want to use the project and not layers to control the display in the QgsLayoutItemMap contrary to this test code (see qgsLayoutItemMap2.keepLayerSet())

1

Found the issue just five minutes after posting...

layout1 = QgsProject.instance().layoutManager().layouts()[0]

qgsLayoutItemMap2 = QgsLayoutItemMap(layout1)
qgsLayoutItemMap2.setId('myNewId')
qgsLayoutItemMap2.attemptSetSceneRect(QRectF(10, 10, 180, 180))
qgsLayoutItemMap2.setFrameEnabled(True)
qgsLayoutItemMap2.setFrameStrokeColor(QColor(255, 0, 0))
extent = QgsRectangle(-122.52, 37.71, -122.35, 37.83)
qgsLayoutItemMap2.setExtent(extent)
layout1.addItem(qgsLayoutItemMap2)

print(qgsLayoutItemMap2.scale()) # Return 60835.889859339615
qgsLayoutItemMap2.setScale(40000.0)
print(qgsLayoutItemMap2.scale()) # Return 39999.999999998035

The clue has been found in code from https://courses.spatialthoughts.com/pyqgis-in-a-day.html#creating-a-pdf-with-title You need to set an extent to avoid the issue I've encountered.

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.