3

I am creating a processing tool where I temporarily load layers in TOC and a layout template and then export the map into an image. Even though I want to have 2 layers on the map, I only want to have one of them in my legend.

How can I exclude the layer(s) in the legend? Do I need to configure this in .qpt or exclude it while reading my layout template?

Here is the part of my code how I add the data and read layout template.

canv = iface.mapCanvas()
project = QgsProject.instance()
root = QgsProject.instance().layerTreeRoot()

# Get checked layer tree objects and stores them in a list
checked_groups = [layer.name() for layer in QgsProject().instance().layerTreeRoot().children() if layer.isVisible()]

# Uncheck  all layers
for group in checked_groups:
    root.findGroup(group).setItemVisibilityChecked(False)

# Add required layers for the map
root.insertLayer(0, vlyr_ezgStats)
vlyr_ezgStats.loadNamedStyle(ezg_qml)
vlyr_ezgStats.triggerRepaint()
root.insertLayer(1, vlyr_geol)

# Load layout tmp
vlyr_geol.loadNamedStyle(geo_qml)
vlyr_geol.triggerRepaint()

# Read the layout temp
templateFile = open(geologische_karte_qpt, 'r')
templateContent = templateFile.read()
templateFile.close()

doc = QDomDocument()
doc.setContent(templateContent)

layout = QgsLayout(project)
layout.initializeDefaults()

# Get bbox of layer for adjusting the map frame
bbox = [feat.geometry().boundingBox() for feat in vlyr_ezgStats.getFeatures()]

items, ok = layout.loadFromTemplate(doc, QgsReadWriteContext(), False)

# Adjust frame
mapFrame = layout.itemById("Map1")
mapFrame.zoomToExtent(bbox[0])
mapFrame.setScale(75591)

# Creates a QgsLayoutExporter object
exporter = QgsLayoutExporter(layout)
image_export_settings = QgsLayoutExporter.ImageExportSettings()
image_export_settings.dpi = 200
image_export_settings.cropToContents = True
image_export_settings.imageSize = QSize(2000, 2000)

# Exports an image of the layout object
exporter.exportToImage(imgDir + '\geologische_karte.png', image_export_settings)

And this is the layout template file

<Layout units="mm" worldFileMap="" printResolution="300" name="wlk_kennzahlen_GeolKarte2">
 <Snapper tolerance="5" snapToItems="1" snapToGuides="1" snapToGrid="0"/>
 <Grid offsetY="0" resolution="15" offsetX="0" offsetUnits="mm" resUnits="mm"/>
 <PageCollection>
  <symbol alpha="1" clip_to_extent="1" name="" type="fill" force_rhr="0">
   <layer class="SimpleFill" locked="0" pass="0" enabled="1">
    <prop k="border_width_map_unit_scale" v="3x:0,0,0,0,0,0"/>
    <prop k="color" v="255,255,255,255"/>
    <prop k="joinstyle" v="miter"/>
    <prop k="offset" v="0,0"/>
    <prop k="offset_map_unit_scale" v="3x:0,0,0,0,0,0"/>
    <prop k="offset_unit" v="MM"/>
    <prop k="outline_color" v="35,35,35,255"/>
    <prop k="outline_style" v="no"/>
    <prop k="outline_width" v="0.26"/>
    <prop k="outline_width_unit" v="MM"/>
    <prop k="style" v="solid"/>
    <data_defined_properties>
     <Option type="Map">
      <Option value="" name="name" type="QString"/>
      <Option name="properties"/>
      <Option value="collection" name="type" type="QString"/>
     </Option>
    </data_defined_properties>
   </layer>
  </symbol>
  <GuideCollection visible="1"/>
 </PageCollection>
 <LayoutItem visibility="1" mapUuid="{30a0683e-6223-435c-977b-ec802a2f3c15}" northMode="0" type="65640" anchorPoint="0" background="false" referencePoint="0" excludeFromExports="0" positionOnPage="196.876,196.7,mm" position="196.876,196.7,mm" templateUuid="{a65c459e-df78-4b63-acfc-72296787d555}" zValue="6" svgFillColor="255,255,255,255" frame="false" file=":/images/north_arrows/layout_default_north_arrow.svg" pictureRotation="0" id="North Arrow" itemRotation="0" outlineWidthM="0.3,mm" opacity="1" size="13.1095,11.5914,mm" svgBorderColor="0,0,0,255" svgBorderWidth="0.2" pictureWidth="9.1828" pictureHeight="11.5914" frameJoinStyle="miter" positionLock="false" blendMode="0" uuid="{a65c459e-df78-4b63-acfc-72296787d555}" resizeMode="0" northOffset="0" groupUuid="">
  <FrameColor alpha="255" red="0" blue="0" green="0"/>
  <BackgroundColor alpha="255" red="255" blue="255" green="255"/>
  <LayoutObject>
   <dataDefinedProperties>
    <Option type="Map">
     <Option value="" name="name" type="QString"/>
     <Option name="properties"/>
     <Option value="collection" name="type" type="QString"/>
    </Option>
   </dataDefinedProperties>
   <customproperties/>
  </LayoutObject>
 </LayoutItem>
 <LayoutItem numSegmentsLeft="0" outlineWidth="0.3" numMapUnitsPerScaleBarUnit="1" height="3" id="" positionLock="false" lineJoinStyle="miter" itemRotation="0" background="false" templateUuid="{5a702fa8-13c3-45a1-aa75-3642d2bec618}" labelVerticalPlacement="0" visibility="1" frameJoinStyle="miter" mapUuid="{30a0683e-6223-435c-977b-ec802a2f3c15}" positionOnPage="1.49516,210.969,mm" numUnitsPerSegment="1" excludeFromExports="0" lineCapStyle="square" boxContentSpace="1" maxBarWidth="150" numSegments="2" uuid="{5a702fa8-13c3-45a1-aa75-3642d2bec618}" frame="false" blendMode="0" referencePoint="6" labelHorizontalPlacement="0" alignment="0" outlineWidthM="0.3,mm" segmentMillimeters="13.2248" segmentSizeMode="0" type="65646" position="1.49516,210.969,mm" labelBarSpace="3" style="Single Box" size="38.2497,12.9476,mm" groupUuid="" unitType="km" opacity="1" zValue="6" unitLabel="km" minBarWidth="50">
  <FrameColor alpha="255" red="0" blue="0" green="0"/>
  <BackgroundColor alpha="255" red="255" blue="255" green="255"/>
  <LayoutObject>
   <dataDefinedProperties>
    <Option type="Map">
     <Option value="" name="name" type="QString"/>
     <Option name="properties"/>
     <Option value="collection" name="type" type="QString"/>
    </Option>
   </dataDefinedProperties>
   <customproperties/>
  </LayoutObject>
  <text-style fontStrikeout="0" fontSizeUnit="Point" textOrientation="horizontal" previewBkgrdColor="255,255,255,255" fontFamily="MS Shell Dlg 2" fontSize="12" fontCapitals="0" fontLetterSpacing="0" multilineHeight="1" textColor="0,0,0,255" fontKerning="1" fontItalic="0" fontWordSpacing="0" fontUnderline="0" blendMode="0" fontSizeMapUnitScale="3x:0,0,0,0,0,0" fontWeight="50" textOpacity="1" namedStyle="">
   <text-buffer bufferSizeMapUnitScale="3x:0,0,0,0,0,0" bufferJoinStyle="128" bufferColor="255,255,255,255" bufferSizeUnits="MM" bufferSize="1" bufferDraw="0" bufferNoFill="1" bufferOpacity="1" bufferBlendMode="0"/>
   <background shapeType="0" shapeSizeType="0" shapeBorderWidth="0" shapeRadiiUnit="MM" shapeFillColor="255,255,255,255" shapeRadiiMapUnitScale="3x:0,0,0,0,0,0" shapeOffsetY="0" shapeOffsetUnit="MM" shapeOffsetMapUnitScale="3x:0,0,0,0,0,0" shapeOpacity="1" shapeBorderWidthMapUnitScale="3x:0,0,0,0,0,0" shapeDraw="0" shapeRotation="0" shapeBlendMode="0" shapeSizeX="0" shapeRadiiX="0" shapeSizeY="0" shapeRotationType="0" shapeRadiiY="0" shapeBorderColor="128,128,128,255" shapeSizeUnit="MM" shapeSizeMapUnitScale="3x:0,0,0,0,0,0" shapeJoinStyle="64" shapeBorderWidthUnit="MM" shapeOffsetX="0" shapeSVGFile=""/>
   <shadow shadowOffsetUnit="MM" shadowOffsetGlobal="1" shadowRadiusMapUnitScale="3x:0,0,0,0,0,0" shadowColor="0,0,0,255" shadowDraw="0" shadowBlendMode="6" shadowOffsetMapUnitScale="3x:0,0,0,0,0,0" shadowRadius="1.5" shadowScale="100" shadowOpacity="0.7" shadowRadiusUnit="MM" shadowOffsetAngle="135" shadowOffsetDist="1" shadowRadiusAlphaOnly="0" shadowUnder="0"/>
   <dd_properties>
    <Option type="Map">
     <Option value="" name="name" type="QString"/>
     <Option name="properties"/>
     <Option value="collection" name="type" type="QString"/>
    </Option>
   </dd_properties>
  </text-style>
  <fillColor alpha="255" red="0" blue="0" green="0"/>
  <fillColor2 alpha="255" red="255" blue="255" green="255"/>
  <strokeColor alpha="255" red="0" blue="0" green="0"/>
 </LayoutItem>
 <LayoutItem wmsLegendHeight="25" id="Legend1" positionLock="false" columnSpace="2" itemRotation="0" map_uuid="{30a0683e-6223-435c-977b-ec802a2f3c15}" background="true" templateUuid="{604c38d7-8bcf-4b16-9134-6e16485654c7}" visibility="1" frameJoinStyle="miter" wmsLegendWidth="50" legendFilterByAtlas="1" positionOnPage="6.25216,4.32842,mm" excludeFromExports="0" uuid="{604c38d7-8bcf-4b16-9134-6e16485654c7}" rasterBorder="1" frame="false" wrapChar="" resizeToContents="1" symbolHeight="4" columnCount="1" rasterBorderWidth="0" fontColor="#000000" symbolAlignment="1" blendMode="0" referencePoint="0" rasterBorderColor="0,0,0,255" boxSpace="2" outlineWidthM="0.3,mm" splitLayer="0" title="" titleAlignment="1" type="65642" symbolWidth="7" position="6.25216,4.32842,mm" equalColumnWidth="0" lineSpacing="1" size="183.6,50.5,mm" groupUuid="" legendFilterByMap="1" opacity="1" zValue="4">
  <FrameColor alpha="255" red="0" blue="0" green="0"/>
  <BackgroundColor alpha="255" red="255" blue="255" green="255"/>
  <LayoutObject>
   <dataDefinedProperties>
    <Option type="Map">
     <Option value="" name="name" type="QString"/>
     <Option name="properties"/>
     <Option value="collection" name="type" type="QString"/>
    </Option>
   </dataDefinedProperties>
   <customproperties/>
  </LayoutObject>
  <styles>
   <style marginBottom="3.5" name="title" alignment="1">
    <styleFont description="MS Shell Dlg 2,16,-1,5,50,0,0,0,0,0" style=""/>
   </style>
   <style name="group" marginTop="3" alignment="1">
    <styleFont description="MS Shell Dlg 2,10,-1,5,50,0,0,0,0,0,Regular" style="Regular"/>
   </style>
   <style name="subgroup" marginTop="3" alignment="1">
    <styleFont description="MS Shell Dlg 2,10,-1,5,50,0,0,0,0,0,Regular" style="Regular"/>
   </style>
   <style name="symbol" marginTop="2.5" alignment="1">
    <styleFont description="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" style=""/>
   </style>
   <style marginLeft="2" name="symbolLabel" marginTop="2" alignment="1">
    <styleFont description="MS Shell Dlg 2,10,-1,5,50,0,0,0,0,0,Regular" style="Regular"/>
   </style>
  </styles>
 </LayoutItem>
 <LayoutItem visibility="1" type="65639" mapRotation="0" followPreset="false" background="true" referencePoint="4" excludeFromExports="0" positionOnPage="106.133,106.133,mm" position="106.133,106.133,mm" templateUuid="{30a0683e-6223-435c-977b-ec802a2f3c15}" zValue="1" frame="true" followPresetName="" id="Map1" itemRotation="0" outlineWidthM="0.6,mm" opacity="1" size="2500,2500,px" labelMargin="0,mm" mapFlags="0" drawCanvasItems="true" keepLayerSet="false" frameJoinStyle="round" positionLock="false" blendMode="0" uuid="{30a0683e-6223-435c-977b-ec802a2f3c15}" groupUuid="">
  <FrameColor alpha="255" red="32" blue="32" green="32"/>
  <BackgroundColor alpha="255" red="255" blue="255" green="255"/>
  <LayoutObject>
   <dataDefinedProperties>
    <Option type="Map">
     <Option value="" name="name" type="QString"/>
     <Option name="properties"/>
     <Option value="collection" name="type" type="QString"/>
    </Option>
   </dataDefinedProperties>
   <customproperties/>
  </LayoutObject>
  <Extent ymin="366908.09658961050445214" ymax="382908.09658961050445214" xmax="494460.53115462587447837" xmin="478460.53115462587447837"/>
  <crs>
   <spatialrefsys>
    <wkt>PROJCRS["MGI / Austria Lambert",BASEGEOGCRS["MGI",DATUM["Militar-Geographische Institut",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4312]],CONVERSION["Austria Lambert",METHOD["Lambert Conic Conformal (2SP)",ID["EPSG",9802]],PARAMETER["Latitude of false origin",47.5,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8821]],PARAMETER["Longitude of false origin",13.3333333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8822]],PARAMETER["Latitude of 1st standard parallel",49,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8823]],PARAMETER["Latitude of 2nd standard parallel",46,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8824]],PARAMETER["Easting at false origin",400000,LENGTHUNIT["metre",1],ID["EPSG",8826]],PARAMETER["Northing at false origin",400000,LENGTHUNIT["metre",1],ID["EPSG",8827]]],CS[Cartesian,2],AXIS["northing (X)",north,ORDER[1],LENGTHUNIT["metre",1]],AXIS["easting (Y)",east,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["unknown"],AREA["Austria"],BBOX[46.4,9.53,49.02,17.17]],ID["EPSG",31287]]</wkt>
    <proj4>+proj=lcc +lat_0=47.5 +lon_0=13.3333333333333 +lat_1=49 +lat_2=46 +x_0=400000 +y_0=400000 +ellps=bessel +towgs84=577.326,90.129,463.919,5.137,1.474,5.297,2.4232 +units=m +no_defs</proj4>
    <srsid>2628</srsid>
    <srid>31287</srid>
    <authid>EPSG:31287</authid>
    <description>MGI / Austria Lambert</description>
    <projectionacronym>lcc</projectionacronym>
    <ellipsoidacronym>EPSG:7004</ellipsoidacronym>
    <geographicflag>false</geographicflag>
   </spatialrefsys>
  </crs>
  <LayerSet/>
  <AtlasMap atlasDriven="0" margin="0.10000000000000001" scalingMode="2"/>
  <labelBlockingItems/>
 </LayoutItem>
 <customproperties>
  <property value="png" key="atlasRasterFormat"/>
  <property key="variableNames"/>
  <property key="variableValues"/>
 </customproperties>
 <Atlas hideCoverage="0" sortFeatures="0" filterFeatures="0" enabled="0" coverageLayer="" pageNameExpression="" filenamePattern="'output_'||@atlas_featurenumber"/>
</Layout>

1 Answer 1

6

Here is short snippet of code to directly remove a layer node from a layout legend by getting a reference to the QgsMapLayer object by name:

# You already have a reference to the project and layout objects
map_layer_to_remove = project.mapLayersByName('Name_of_layer_to_exclude_from_layout_legend')[0]
legend = [i for i in layout.items() if isinstance(i, QgsLayoutItemLegend)][0]
legend.setAutoUpdateModel(False)
legend.model().rootGroup().removeLayer(map_layer_to_remove)
legend.adjustBoxSize()
layout.refresh()
0

Your Answer

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

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