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

myAtlas=layout.atlas() # make the layout as an atlas


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

map = QgsLayoutItemMap(layout) # adding the map
map.setRect(20, 20, 20, 20)#Set Map Extent
map.setAtlasMargin(0.2) #20%
rectangle = QgsRectangle(-244516.858, 169608.638, -243208.118, 170778.898)#still required to start

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.setMinimumSize(QgsLayoutSize(34.002, 7, QgsUnitTypes.LayoutMillimeters))
currPage = myAtlas.currentFeatureNumber()
totPage = myAtlas.count()
page.setText("Page : '%d' / '%d'" % (currPage, totPage)) 

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 : example


1 Answer 1


You can use the following structure:

# previous lines

page_label = QgsLayoutItemLabel(layout)

# other label settings here

text = "[% 'Page: ' + to_string(@atlas_featurenumber ) + '/' + to_string(@atlas_totalfeatures)%]"

for page in range(myAtlas.count()):

enter image description here

  • I can see your Ubuntu 😍
    – Taras
    Commented Jan 21, 2021 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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