Exemple #1
0
def set_legend(layout: QgsPrintLayout, tree: QgsLayerTree, layer: QgsLayer, item_id: str):
  '''Sets the Legend items'''
  logging.info(f'setting legend: {item_id}')
  item = layout.itemById(item_id)

  # set layer as root for legend
  tree.addLayer(layer)
  model = item.model()
  model.setRootGroup(tree)
  root = model.rootGroup().findLayer(layer)
  
  # hide the node title
  QgsLegendRenderer.setNodeLegendStyle(root, QgsLegendStyle.Hidden)

  # hide the node with label: Band 1 (Gray)
  if isinstance(layer, QgsRasterLayer):
    nodes = model.layerLegendNodes(root)
    if nodes[0].data(0) == 'Band 1 (Gray)':
      indexes = list(range(1, len(nodes)))
      QgsMapLayerLegendUtils.setLegendNodeOrder(root, indexes)
      model.refreshLayerLegend(root)
    def with_legend_btn_run(self):

        project = QgsProject.instance()
        self.checked_layers = []
        root = project.layerTreeRoot()
        for child in root.children():
            if child.isVisible() and isinstance(child, QgsLayerTreeLayer):
                self.checked_layers.append(child.name())

            if child.isVisible() and isinstance(child, QgsLayerTreeGroup):
                self.get_group_layers(child)

        layersToAdd = [
            layer for layer in project.mapLayers().values()
            if layer.name() in sorted(self.checked_layers, reverse=False)
        ]
        layers_names_length = [
            len(layer.name()) for layer in project.mapLayers().values()
            if layer.name() in sorted(self.checked_layers, reverse=False)
        ]
        maxlen = max(layers_names_length)

        root = QgsLayerTree()
        for layer in layersToAdd:
            root.addLayer(layer)

        model = QgsLayerTreeModel(root)
        lenlen = model.rowCount()
        view = QgsLayerTreeView()
        view.setModel(model)

        view.setFixedHeight(lenlen * 20)
        view.setFixedWidth(maxlen * 10)

        legendIm = QImage(QWidget.grab(view))
        legendpath = self.plugin_dir + "\\legend.png"
        legendIm.save(legendpath)

        legendIm = Image.open(legendpath)
        #legendIm = legendIm.imageData()
        legendWidth, legendHeight = legendIm.size

        main_image = QImage(QWidget.grab(self.iface.mapCanvas()))
        mainpath = self.plugin_dir + "\\main.png"
        main_image.save(mainpath)

        main_image = Image.open(mainpath).convert("RGBA")
        width, height = main_image.size

        d = ImageDraw.Draw(main_image)
        font = ImageFont.truetype("arial.ttf", 16)
        d.text(((width / 2.5) + len(project.title()), 10),
               project.title(),
               fill='black',
               font=font)

        if abs(height - width) < 150:
            sq_fit_size = legendWidth
            height = legendHeight
        else:
            sq_fit_size = width

        if width > sq_fit_size and height > sq_fit_size:
            if width > height:
                height = int((sq_fit_size / width) * height)
                width = sq_fit_size
            else:
                width = int((sq_fit_size / height) * width)
                height = sq_fit_size
                main_image = main_image.resize((width, height))

        main_image.paste(legendIm,
                         (max(width - legendWidth, 0), height - legendHeight))
        finalpath = self.plugin_dir + "\\main.png"
        main_image.save(finalpath)

        QApplication.clipboard().setImage(QImage(finalpath))
        self.iface.messageBar().pushMessage(
            'QCopycanvas',
            'Copied map canvas to clipboard with legend',
            level=Qgis.Success,
            duration=2)