I am learning PyQGIS 3 for a few weeks and I am trying to understand how to create an atlas with PyQGIS 3 from the beginning.
UPDATE : Here is where I am now :
project = QgsProject.instance()
client = os.path.basename(project.homePath()) # get the name of the directory
manager = project.layoutManager()
layoutName = client + " - Atlas paysage"
layouts_list = manager.printLayouts()
for layout in layouts_list:
if layout.name() == layoutName: #if there is already a layout with the same name
manager.removeLayout(layout) # remove it
layout = QgsPrintLayout(project)
layout.initializeDefaults() #create default map canvas
layout.setName(layoutName)
myAtlas=layout.atlas() # make the layout as an atlas
myAtlas.setPageNameExpression("attribute(get_feature('plan_de_ferme','diagramme',attribute('diagramme')),'comment')")
myAtlas.setSortExpression('diagramme') # order the pages regarding the value in 'diagramme' (integer beginning at 1)
manager.addLayout(layout) #add the layout in the layout manager
layout.atlas().setEnabled(True) # this check the box "generate an atlas"
cover = project.mapLayersByName(os.path.basename(path) + '_Atlas')[0]
#layer used to define the number of page and the extent of each one
myAtlas.setCoverageLayer(cover)
map = QgsLayoutItemMap(layout) # adding the map
map.setRect(20, 20, 20, 20)#Set Map Extent
map.setAtlasDriven
map.setAtlasMargin(0.2) #20%
rectangle = QgsRectangle(-244516.858, 169608.638, -243208.118, 170778.898)#still required to start
map.setExtent(rectangle)
layout.addLayoutItem(map)
I don't understand how to define page number and make it change for each page.
page = QgsLayoutItemLabel(layout)
page.setFont(QFont("Ms Shell Dlg 2", 10))
page.attemptMove(QgsLayoutPoint(231.326, 208, QgsUnitTypes.LayoutMillimeters))
page.setHAlign(Qt.AlignRight)
page.setVAlign(Qt.AlignVCenter)
page.setMinimumSize(QgsLayoutSize(34.002, 7, QgsUnitTypes.LayoutMillimeters))
currPage = myAtlas.currentFeatureNumber()
totPage = myAtlas.count()
page.setText("Page : '%d' / '%d'" % (currPage, totPage))
layout.addLayoutItem(page)
The last line doesn't work because of the one above. I think one of the problems is that when I open the layout created, atlas parameters are well defined but I need to click on "overview of the atlas" to see the several pages, and to make the following code returning the correct number of pages: myAtlas.count()
As a result, I would like to add a label indicating the current page number (changing for each page) above the total number of pages. for example if I have 3 pages in my atlas :