1

When I am running the code in QGIS python console, I am getting an error -

RuntimeError: wrapped C/C++ object of type QgsPrintLayout has been deleted

from PyQt5.QtCore import QTimer

fileName = 'D:\\UCC\\exported' # exported is a prefix for the file names
boundaryLayer = QgsProject.instance().mapLayersByName('Cooling_Towers')[0]
QgsProject.instance().layerTreeRoot().findLayer(boundaryLayer.id()).setItemVisibilityChecked(True)

otherLayers = []
for layer in QgsProject.instance().mapLayers().values():
    if layer.name().startswith("M_"):
        otherLayers.append(layer.name())

count = 0
def prepareMap(): # Arrange layers
    for layer in QgsProject.instance().mapLayers().values():
        if layer.name().startswith("M_"):
            QgsProject.instance().layerTreeRoot().findLayer(layer).setItemVisibilityChecked(False)
    for layer in QgsProject.instance().mapLayers().values():
        if layer.name().startswith(otherLayers[count]):
            QgsProject.instance().layerTreeRoot().findLayer(layer).setItemVisibilityChecked(True)
            qgis.utils.iface.setActiveLayer(layer)
            qgis.utils.iface.zoomToActiveLayer()
            project = QgsProject.instance()
            manager = project.layoutManager()
            layout = QgsPrintLayout(project)
            layoutName = 'Layout'
            #initializes default settings for blank print layout canvas
            layout.initializeDefaults()
            layout.setName(layoutName)
            manager.addLayout(layout)
            #layoutName = "PrintLayout"
            layouts_list = manager.printLayouts()
            # remove any duplicate layouts
            for layout in layouts_list:
                if layout.name() == layoutName:
                    manager.removeLayout(layout)
            
            page_size =QgsLayoutSize(5000, 5000, QgsUnitTypes.LayoutPixels)
            pc = layout.pageCollection()
            page = pc.pages()[0]
            page.setPageSize(page_size)

            # create map item in the layout
            map = QgsLayoutItemMap(layout)
            map.setKeepLayerSet(True)
            map.setLayers([layer, boundaryLayer])
            map.setRect(20, 20, 20, 20)
            
            #rect = QgsRectangle(ms.fullExtent())
            rect = QgsRectangle(-8232312.3, 4993694.4, -8231302.8, 4994703.9)
            map.setExtent(rect)
            map.attemptResize(QgsLayoutSize(423.333, 423.333, QgsUnitTypes.LayoutMillimeters))
            layout.addLayoutItem(map)
                       
            layout = manager.layoutByName(layoutName)
            exporter = QgsLayoutExporter(layout)

            fn = 'D:\\layout_export' + str(count) + '.png'
            exporter.exportToImage(fn, QgsLayoutExporter.ImageExportSettings())
            
            
            #map.refresh()
            
    QTimer.singleShot(30000, exportMap) # Wait a second and export the map

 # Save the map as a PNG
def exportMap():
    global count # We need this because we'll modify its value
    if count < len(otherLayers)-1:
        QTimer.singleShot(10000, prepareMap) # Wait a second and prepare next map
    count += 1

prepareMap()

Reference - Iterating over layers and exporting them as PNG images with PyQGIS in standalone script

https://data.library.virginia.edu/how-to-create-and-export-print-layouts-in-python-for-qgis-3/

1 Answer 1

1

This error appears when you print a layout with a name that is already used for other layout.

2
  • Ok.. How could I resolve it? I mean what changes should I do with my code? @Mayo Jul 15, 2022 at 22:05
  • There are many ways to do this, the important think is that every layout must have a different name and in your code you are naming all the layouts "Layout". You can name each layouts with the name of the layer you are printing: layoutName = layer.name().
    – Mayo
    Jul 15, 2022 at 22:23

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.