2

I have a script that takes an input layer, selects attributes by date, makes another layer from these attributes, and prints the map to pdf. It runs and produces the pdf, but once it runs, the input layer becomes invisible, and all other layers lose their labeling. I've tried refreshing the map canvas, which didn't work.

After experimenting, it appears that my input layer and labeling disappear when code writes features to a new layer. (noted in comments)

Code below (omitting processing algorithm template and imports for brevity):

    # Selects input points layer as active layer
    temporaryCompaction = QgsProject.instance().mapLayersByName(str(source.sourceName()))[0]
    iface.setActiveLayer(temporaryCompaction)
    iface.mapCanvas().setSelectionColor(QColor('green'))

    feedback.pushInfo(source.sourceName())

    # Selects attributes from layer by date
    testDate = input_date[:10]
    expression = f"to_date(Date) = to_date('{testDate}', 'yyyy-MM-dd')"
    feedback.pushInfo(expression)
    temporaryCompaction.selectByExpression(expression)

    # Writes selected features to a new layer - input layer disappears here
    fn = r'J:\Field\Daily Report Figures' + '\\' + testDate + '.gpkg'
    writer = QgsVectorFileWriter.writeAsVectorFormat(temporaryCompaction, fn, 'utf-8', driverName='GPKG', onlySelected=True)
    iface.addVectorLayer(fn, '', 'ogr')
    del(writer)

    # Creates variable for temporary layer
    tempLayer = QgsProject.instance().mapLayersByName(str(testDate))[0]

    # Adds buffer & labels to tempLayer
    layer_settings  = QgsPalLayerSettings()
    text_format = QgsTextFormat()

    text_format.setFont(QFont("Arial", 8))
    text_format.setSize(8)

    buffer_settings = QgsTextBufferSettings()
    buffer_settings.setEnabled(True)
    buffer_settings.setSize(1)
    buffer_settings.setColor(QColor(31,120,180))

    text_format.setBuffer(buffer_settings)
    layer_settings.setFormat(text_format)

    layer_settings.fieldName = "Test number"
    # layer_settings.placement = 1 # this doesn't work in QGIS 3.28; documentation is unchanged?
    # layer_settings.quadOffset = 2 # this doesn't work in QGIS 3.28; documentation is unchanged?
    layer_settings.dist = 0.5
    layer_settings.xOffset = 1.0
    layer_settings.yOffset = 0.0

    layer_settings.enabled = True

    layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
    tempLayer.setLabelsEnabled(True)
    tempLayer.setLabeling(layer_settings)
    tempLayer.triggerRepaint()

    # Set points symbology for tempLayer: color and stroke width/color
    single_symbol_renderer = tempLayer.renderer()
    symbol = single_symbol_renderer.symbol()
    symbol.setColor(QColor.fromRgb(231,113,72))
    symbol.symbolLayer(0).setStrokeColor(QColor(31,120,180))
    symbol.symbolLayer(0).setStrokeWidth(0.5)

    # Create variables for all other layers to print to PDF
    buildingsOne = QgsProject.instance().mapLayersByName('Buildings B-1 to B-8')[0]
    buildingsTwo = QgsProject.instance().mapLayersByName('Buildings A-1 to A-2')[0]
    boundary = QgsProject.instance().mapLayersByName('Boundary')[0]
    ponds = QgsProject.instance().mapLayersByName('PONDS')[0]
    rowRoads = QgsProject.instance().mapLayersByName('ROW_ROADS')[0]
    baseMap = QgsProject.instance().mapLayersByName('ESRI Satellite')[0]

    # Print to PDF
    settings = iface.mapCanvas().mapSettings()
    settings.setLayers([tempLayer, buildingsOne, buildingsTwo, boundary, ponds, rowRoads, baseMap])

    printer = QPrinter(QPrinter.HighResolution)
    printer.setOutputFileName(r'J:\Field\Daily Report Figures' + '\\' + 'fr' + testDate + '.pdf')
    printer.setOutputFormat(QPrinter.PdfFormat)

    printer.setPageOrientation(QPageLayout.Orientation.Portrait)
    outputSize = settings.outputSize()
    printer.setPaperSize(QSizeF(outputSize * 25.4 / settings.outputDpi()), QPrinter.Millimeter)
    printer.setPageMargins(.5, .5, .5, .5, QPrinter.Millimeter)
    printer.setResolution(settings.outputDpi())
    #settings.setFlag(Qgis.MapSettingsFlag.ForceVectorOutput, True)

    dest_painter = QPainter(printer)
    dest_painter.setRenderHint(QPainter.Antialiasing)

    render_job = QgsMapRendererCustomPainterJob(settings, dest_painter)
    render_job.renderSynchronously()

    dest_painter.end()

    QgsProject.instance().removeMapLayer(tempLayer.id())

    return {}

1 Answer 1

1

Solved my own problem!

I narrowed it down to:

iface.addVectorLayer(fn, '', 'ogr')

as the point where things started disappearing from my map. I replaced it with the following:

addMe = QgsVectorLayer(fn, testDate, 'ogr')
QgsProject.instance().addMapLayer(addMe)

The script runs and everything remains on the map.

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.