1

I iteratively create .qgs projects, load different layers in them, create a layout and export the maps. The .qgs projects are created but when I open them, my custom layout is not there! Therefore it was not saved within the project. What did I miss?

Here is my piece of code:

processing_name = ["qgs_t1", "qgs_t2", "qgs_t3"]
anriss_list = ["C:\\MyData\\A300.shp", "C:\\MyData\\B300.shp", "C:\\MyData\\C300.shp"]
anriss_name_list = ["A300","B300","C300"]

for i in range(len(3)):
    # create project
    qgis_project_name = "C:\\ResultFolder\\" + processing_name[i] + ".qgs"

    project = QgsProject.instance()
    project.setCrs(QgsCoordinateReferenceSystem(21781))

    # add vector layer
    iface.mainWindow().blockSignals(True)
    shplayer = iface.addVectorLayer(anriss_list[i], anriss_name_list[i], "ogr")
    if not shplayer.isValid():
       print("Anriss .shp failed to load!")
    shplayer.setCrs(QgsCoordinateReferenceSystem(21781))

    project.addMapLayer(shplayer)

    #-- Create custom caneva
    manager = project.layoutManager()
    layout_name = 'my_custom_layout'
    layout_list = manager.printLayouts()

    layout = QgsPrintLayout(project)
    layout.setName(layout_name)
    layout.initializeDefaults()
    manager.addLayout(layout)

    #--- create map item

    map1 = QgsLayoutItemMap(layout) # create Layout item
    map1.setRect(QRectF(10, 10, 210, 90)) # set the map item rectangle
    map1.setPos(10,10) # map item upper left corner position
    map1.setFrameEnabled(True) # to have a map black border

    ms = QgsMapSettings()
    ms.setLayers([shplayer]) # set layer to be mapped
    map1_extent = QgsRectangle(shplayer.extent())
    map1_extent.scale(1.0)
    ms.setExtent(map1_extent)
    map1.setExtent(map1_extent)

    layout.addLayoutItem(map1)
    map1.attemptMove(QgsLayoutPoint(10,10))
    map1.attemptResize(QgsLayoutSize(210,90))


    # export map in .pdf
    exporter = QgsLayoutExporter(layout)
    exporter.exportToPdf("C:\\mapstest.pdf", QgsLayoutExporter.PdfExportSettings())


    project.write(qgis_project_name[i])
    project.clear()
1

Oh that was a missing line "project.write()" before exporting the .pdf! Problem solved

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.