Exemplo n.º 1
0
    def testRemoveLayout(self):
        project = QgsProject()
        layout = QgsPrintLayout(project)
        layout.setName('test layout')

        self.manager = QgsLayoutManager(project)
        layout_removed_spy = QSignalSpy(self.manager.layoutRemoved)
        layout_about_to_be_removed_spy = QSignalSpy(self.manager.layoutAboutToBeRemoved)
        # tests that layout still exists when layoutAboutToBeRemoved is fired
        self.manager.layoutAboutToBeRemoved.connect(self.layoutAboutToBeRemoved)

        # not added, should fail
        self.assertFalse(self.manager.removeLayout(layout))
        self.assertEqual(len(layout_removed_spy), 0)
        self.assertEqual(len(layout_about_to_be_removed_spy), 0)

        self.assertTrue(self.manager.addLayout(layout))
        self.assertEqual(self.manager.layouts(), [layout])
        self.assertTrue(self.manager.removeLayout(layout))
        self.assertEqual(len(self.manager.layouts()), 0)
        self.assertEqual(len(layout_removed_spy), 1)
        self.assertEqual(layout_removed_spy[0][0], 'test layout')
        self.assertEqual(len(layout_about_to_be_removed_spy), 1)
        self.assertEqual(layout_about_to_be_removed_spy[0][0], 'test layout')
        self.assertTrue(self.aboutFired)
        self.manager = None
Exemplo n.º 2
0
    def testGenerateUniqueTitle(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        self.assertEqual(manager.generateUniqueTitle(QgsMasterLayoutInterface.PrintLayout), 'Layout 1')
        self.assertEqual(manager.generateUniqueTitle(QgsMasterLayoutInterface.Report), 'Report 1')

        layout = QgsPrintLayout(project)
        layout.setName(manager.generateUniqueTitle())
        manager.addLayout(layout)

        self.assertEqual(manager.generateUniqueTitle(), 'Layout 2')
        self.assertEqual(manager.generateUniqueTitle(QgsMasterLayoutInterface.Report), 'Report 1')
        layout2 = QgsPrintLayout(project)
        layout2.setName(manager.generateUniqueTitle())
        manager.addLayout(layout2)

        self.assertEqual(manager.generateUniqueTitle(), 'Layout 3')

        report1 = QgsReport(project)
        report1.setName(manager.generateUniqueTitle(QgsMasterLayoutInterface.Report))
        manager.addLayout(report1)
        self.assertEqual(manager.generateUniqueTitle(QgsMasterLayoutInterface.Report), 'Report 2')

        manager.clear()
        self.assertEqual(manager.generateUniqueTitle(), 'Layout 1')
        self.assertEqual(manager.generateUniqueTitle(QgsMasterLayoutInterface.Report), 'Report 1')
Exemplo n.º 3
0
    def testReadWriteXml(self):
        p = QgsProject()
        l = QgsPrintLayout(p)
        l.setName('my layout')
        l.setUnits(QgsUnitTypes.LayoutInches)
        collection = l.pageCollection()

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A6')
        collection.addPage(page)

        grid = l.gridSettings()
        grid.setResolution(QgsLayoutMeasurement(5, QgsUnitTypes.LayoutPoints))

        g1 = QgsLayoutGuide(Qt.Horizontal, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters),
                            l.pageCollection().page(0))
        l.guides().addGuide(g1)

        snapper = l.snapper()
        snapper.setSnapTolerance(7)

        # add some items
        item1 = QgsLayoutItemMap(l)
        item1.setId('xxyyxx')
        l.addItem(item1)
        item2 = QgsLayoutItemMap(l)
        item2.setId('zzyyzz')
        l.addItem(item2)

        l.setReferenceMap(item2)

        doc = QDomDocument("testdoc")
        elem = l.writeXml(doc, QgsReadWriteContext())

        l2 = QgsPrintLayout(p)
        self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext()))
        self.assertEqual(l2.name(), 'my layout')
        self.assertEqual(l2.units(), QgsUnitTypes.LayoutInches)

        collection2 = l2.pageCollection()
        self.assertEqual(collection2.pageCount(), 1)
        self.assertAlmostEqual(collection2.page(0).pageSize().width(), 105, 4)
        self.assertEqual(collection2.page(0).pageSize().height(), 148)
        self.assertEqual(l2.gridSettings().resolution().length(), 5.0)
        self.assertEqual(l2.gridSettings().resolution().units(), QgsUnitTypes.LayoutPoints)
        self.assertEqual(l2.guides().guidesOnPage(0)[0].orientation(), Qt.Horizontal)
        self.assertEqual(l2.guides().guidesOnPage(0)[0].position().length(), 5.0)
        self.assertEqual(l2.guides().guidesOnPage(0)[0].position().units(), QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(l2.snapper().snapTolerance(), 7)

        # check restored items
        new_item1 = l2.itemByUuid(item1.uuid())
        self.assertTrue(new_item1)
        self.assertEqual(new_item1.id(), 'xxyyxx')
        new_item2 = l2.itemByUuid(item2.uuid())
        self.assertTrue(new_item2)
        self.assertEqual(new_item2.id(), 'zzyyzz')
        self.assertEqual(l2.referenceMap().id(), 'zzyyzz')
Exemplo n.º 4
0
    def testCombo(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        layout = QgsPrintLayout(project)
        layout.setName('ccc')
        self.assertTrue(manager.addLayout(layout))
        layout2 = QgsPrintLayout(project)
        layout2.setName('bbb')
        self.assertTrue(manager.addLayout(layout2))
        r = QgsReport(project)
        r.setName('ddd')
        manager.addLayout(r)

        combo = QgsLayoutComboBox(None, manager)
        spy = QSignalSpy(combo.layoutChanged)
        self.assertEqual(combo.count(), 3)

        self.assertEqual(combo.itemText(0), 'bbb')
        self.assertEqual(combo.itemText(1), 'ccc')
        self.assertEqual(combo.itemText(2), 'ddd')

        self.assertEqual(combo.layout(0), layout2)
        self.assertEqual(combo.layout(1), layout)
        self.assertEqual(combo.layout(2), r)

        combo.setCurrentLayout(None)
        self.assertEqual(combo.currentLayout(), None)
        self.assertEqual(len(spy), 1)
        combo.setCurrentLayout(layout)
        self.assertEqual(combo.currentLayout(), layout)
        self.assertEqual(len(spy), 2)
        combo.setCurrentLayout(r)
        self.assertEqual(combo.currentLayout(), r)
        self.assertEqual(len(spy), 3)
        combo.setCurrentLayout(layout2)
        self.assertEqual(combo.currentLayout(), layout2)
        self.assertEqual(len(spy), 4)

        combo.setAllowEmptyLayout(True)
        self.assertEqual(combo.count(), 4)
        self.assertEqual(combo.itemText(0), '')
        self.assertEqual(combo.itemText(1), 'bbb')
        self.assertEqual(combo.itemText(2), 'ccc')
        self.assertEqual(combo.itemText(3), 'ddd')
        combo.setCurrentLayout(None)
        self.assertEqual(combo.currentIndex(), 0)

        combo.setFilters(QgsLayoutManagerProxyModel.FilterPrintLayouts)
        self.assertEqual(combo.count(), 3)
        self.assertEqual(combo.itemText(0), '')
        self.assertEqual(combo.itemText(1), 'bbb')
        self.assertEqual(combo.itemText(2), 'ccc')

        combo.setFilters(QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(combo.filters(), QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(combo.count(), 2)
        self.assertEqual(combo.itemText(0), '')
        self.assertEqual(combo.itemText(1), 'ddd')
Exemplo n.º 5
0
    def testExpressionInText(self):
        """Test expressions embedded in legend node text"""

        point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
        point_layer = QgsVectorLayer(point_path, 'points', 'ogr')

        layout = QgsPrintLayout(QgsProject.instance())
        layout.setName('LAYOUT')
        layout.initializeDefaults()

        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
        map.setFrameEnabled(True)
        map.setLayers([point_layer])
        layout.addLayoutItem(map)
        map.setExtent(point_layer.extent())

        legend = QgsLayoutItemLegend(layout)
        legend.setTitle("Legend")
        legend.attemptSetSceneRect(QRectF(120, 20, 100, 100))
        legend.setFrameEnabled(True)
        legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle('')
        legend.setLegendFilterByMapEnabled(False)
        legend.setStyleFont(QgsLegendStyle.Title, QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Group, QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Subgroup, QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Symbol, QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.SymbolLabel, QgsFontUtils.getStandardTestFont('Bold', 16))

        legend.setAutoUpdateModel(False)

        QgsProject.instance().addMapLayers([point_layer])
        s = QgsMapSettings()
        s.setLayers([point_layer])

        group = legend.model().rootGroup().addGroup("Group [% 1 + 5 %] [% @layout_name %]")
        layer_tree_layer = group.addLayer(point_layer)
        layer_tree_layer.setCustomProperty("legend/title-label", 'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')
        QgsMapLayerLegendUtils.setLegendNodeUserLabel(layer_tree_layer, 0, 'xxxx')
        legend.model().refreshLayerLegend(layer_tree_layer)
        legend.model().layerLegendNodes(layer_tree_layer)[0].setUserLabel('bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')

        layout.addLayoutItem(legend)
        legend.setLinkedMap(map)

        map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))

        checker = QgsLayoutChecker(
            'composer_legend_expressions', layout)
        checker.setControlPathPrefix("composer_legend")
        result, message = checker.testLayout()
        self.assertTrue(result, message)

        QgsProject.instance().removeMapLayers([point_layer.id()])
Exemplo n.º 6
0
    def testReadWriteXml(self):
        """
        Test reading and writing layout manager state to XML
        """
        project = QgsProject()
        manager = QgsLayoutManager(project)

        # add a bunch of layouts
        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        layout3 = QgsPrintLayout(project)
        layout3.setName('test layout3')

        manager.addLayout(layout)
        manager.addLayout(layout2)
        manager.addLayout(layout3)

        # save to xml
        doc = QDomDocument("testdoc")
        elem = manager.writeXml(doc)
        doc.appendChild(elem)

        # restore from xml
        project2 = QgsProject()
        manager2 = QgsLayoutManager(project2)
        self.assertTrue(manager2.readXml(elem, doc))

        self.assertEqual(len(manager2.layouts()), 3)
        names = [c.name() for c in manager2.layouts()]
        self.assertCountEqual(names, ['test layout', 'test layout2', 'test layout3'])
Exemplo n.º 7
0
    def testAddLayout(self):
        project = QgsProject()
        layout = QgsPrintLayout(project)
        layout.setName('test layout')

        manager = QgsLayoutManager(project)

        layout_about_to_be_added_spy = QSignalSpy(manager.layoutAboutToBeAdded)
        layout_added_spy = QSignalSpy(manager.layoutAdded)
        self.assertTrue(manager.addLayout(layout))
        self.assertEqual(len(layout_about_to_be_added_spy), 1)
        self.assertEqual(layout_about_to_be_added_spy[0][0], 'test layout')
        self.assertEqual(len(layout_added_spy), 1)
        self.assertEqual(layout_added_spy[0][0], 'test layout')

        # adding it again should fail
        self.assertFalse(manager.addLayout(layout))

        # try adding a second layout
        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        self.assertTrue(manager.addLayout(layout2))
        self.assertEqual(len(layout_added_spy), 2)
        self.assertEqual(layout_about_to_be_added_spy[1][0], 'test layout2')
        self.assertEqual(len(layout_about_to_be_added_spy), 2)
        self.assertEqual(layout_added_spy[1][0], 'test layout2')

        # adding a layout with duplicate name should fail
        layout3 = QgsPrintLayout(project)
        layout3.setName('test layout2')
        self.assertFalse(manager.addLayout(layout3))
Exemplo n.º 8
0
    def testDuplicateLayout(self):
        """
        Test duplicating layouts
        """
        project = QgsProject()
        manager = QgsLayoutManager(project)
        doc = QDomDocument("testdoc")
        self.assertFalse(manager.duplicateLayout(None, 'dest'))

        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        layout.initializeDefaults()
        manager.addLayout(layout)
        # duplicate name
        self.assertFalse(manager.duplicateLayout(layout, 'test layout'))
        result = manager.duplicateLayout(layout, 'dupe layout')

        self.assertTrue(result)
        # make sure result in stored in manager
        self.assertEqual(result, manager.layoutByName('dupe layout'))
        self.assertEqual(result.name(), 'dupe layout')
        self.assertEqual(result.pageCollection().pageCount(), 1)
    def get_print_layout(self):
        template_path = self.getTemplateFilePath()
        if not os.path.isfile(template_path):
            msg = 'The requested template {} is not currently available.'.format(template_path)
            QMessageBox.critical(self.iface.mainWindow(), 'Template Not Found', msg)
            return

        # Create a new print layout with name equal to the project title
        project = QgsProject.instance()
        layout_manager = project.layoutManager()
        existing_print_layout = layout_manager.layoutByName(self.ui.titleLineEdit.text())
        if existing_print_layout:
            layout_manager.removeLayout(existing_print_layout)
        print_layout = QgsPrintLayout(project)
        print_layout.setName(self.ui.titleLineEdit.text())
        layout_manager.addLayout(print_layout)

        # Load the template file
        try:
            tree = ET.parse(template_path)
            doc = QDomDocument()
            doc.setContent(ET.tostring(tree.getroot()))
        except IOError:
            # problem reading xml template
            msg = 'The requested template {} could not be read.'.format(template_path)
            QMessageBox.critical(self.iface.mainWindow(), 'Failed to Read Template', msg)
            return
        except:
            # Unexpected problem
            msg = 'An unexpected error occurred while reading {}:\n\n{}'.format(template_path, traceback.format_exc())
            QMessageBox.critical(self.iface.mainWindow(), 'Failed to Read Template', msg)
            return

        if not print_layout.loadFromTemplate(doc, QgsReadWriteContext(), True):
            msg = 'loadFromTemplate returned False.'
            QMessageBox.critical(self.iface.mainWindow(), 'Failed to Read Template', msg)
            return

        return print_layout
Exemplo n.º 10
0
    def testRenameSignal(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        layout = QgsPrintLayout(project)
        layout.setName('c1')
        manager.addLayout(layout)
        layout2 = QgsPrintLayout(project)
        layout2.setName('c2')
        manager.addLayout(layout2)

        layout_renamed_spy = QSignalSpy(manager.layoutRenamed)
        layout.setName('d1')
        self.assertEqual(len(layout_renamed_spy), 1)
        # self.assertEqual(layout_renamed_spy[0][0], layout)
        self.assertEqual(layout_renamed_spy[0][1], 'd1')
        layout2.setName('d2')
        self.assertEqual(len(layout_renamed_spy), 2)
        # self.assertEqual(layout_renamed_spy[1][0], layout2)
        self.assertEqual(layout_renamed_spy[1][1], 'd2')
Exemplo n.º 11
0
    def testLayouts(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        layout3 = QgsPrintLayout(project)
        layout3.setName('test layout3')

        manager.addLayout(layout)
        self.assertEqual(manager.layouts(), [layout])
        manager.addLayout(layout2)
        self.assertEqual(set(manager.layouts()), {layout, layout2})
        manager.addLayout(layout3)
        self.assertEqual(set(manager.layouts()), {layout, layout2, layout3})
Exemplo n.º 12
0
    def testLayoutsByName(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)

        # add a bunch of layouts
        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        layout3 = QgsPrintLayout(project)
        layout3.setName('test layout3')

        manager.addLayout(layout)
        manager.addLayout(layout2)
        manager.addLayout(layout3)

        self.assertFalse(manager.layoutByName('asdf'))
        self.assertEqual(manager.layoutByName('test layout'), layout)
        self.assertEqual(manager.layoutByName('test layout2'), layout2)
        self.assertEqual(manager.layoutByName('test layout3'), layout3)
Exemplo n.º 13
0
    def testClear(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)

        # add a bunch of layouts
        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        layout3 = QgsPrintLayout(project)
        layout3.setName('test layout3')

        manager.addLayout(layout)
        manager.addLayout(layout2)
        manager.addLayout(layout3)

        layout_removed_spy = QSignalSpy(manager.layoutRemoved)
        layout_about_to_be_removed_spy = QSignalSpy(manager.layoutAboutToBeRemoved)
        manager.clear()
        self.assertEqual(len(manager.layouts()), 0)
        self.assertEqual(len(layout_removed_spy), 3)
        self.assertEqual(len(layout_about_to_be_removed_spy), 3)
Exemplo n.º 14
0
    def testClear(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)

        # add a bunch of layouts
        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        layout3 = QgsPrintLayout(project)
        layout3.setName('test layout3')

        manager.addLayout(layout)
        manager.addLayout(layout2)
        manager.addLayout(layout3)

        layout_removed_spy = QSignalSpy(manager.layoutRemoved)
        layout_about_to_be_removed_spy = QSignalSpy(
            manager.layoutAboutToBeRemoved)
        manager.clear()
        self.assertEqual(len(manager.layouts()), 0)
        self.assertEqual(len(layout_removed_spy), 3)
        self.assertEqual(len(layout_about_to_be_removed_spy), 3)
Exemplo n.º 15
0
    def test_move_chart_in_layout(self):
        """
        Test moving charts in layout plot up and down
        """
        # print('moving charts in layout plot up and down')

        # create project and layout
        project = QgsProject.instance()
        layout = QgsPrintLayout(project)
        layout_name = "PrintLayoutMovingUpDown"
        layout.initializeDefaults()
        layout.setName(layout_name)
        manager = project.layoutManager()
        self.assertEqual(True, manager.addLayout(layout))
        layout = manager.layoutByName(layout_name)
        layout_plot = PlotLayoutItem(layout)
        self.assertEqual(len(layout_plot.plot_settings), 1)
        # self.assertEqual(len(layout.items()), 0)
        layout.addLayoutItem(layout_plot)
        # self.assertEqual(len(layout.items()), 1)
        plot_dialog = PlotLayoutItemWidget(None, layout_plot)

        # add second plot
        plot_dialog.add_plot()
        self.assertEqual(len(layout_plot.plot_settings), 2)

        # edit first plot
        plot_dialog.setDockMode(True)
        plot_dialog.show_properties()
        plot_property_panel = plot_dialog.panel
        plot_property_panel.set_plot_type('violin')
        self.assertEqual(plot_property_panel.ptype, 'violin')
        plot_property_panel.acceptPanel()
        plot_property_panel.destroy()

        # edit second plot
        plot_dialog.plot_list.setCurrentRow(1)
        plot_dialog.show_properties()
        plot_property_panel = plot_dialog.panel
        plot_property_panel.set_plot_type('bar')
        self.assertEqual(plot_property_panel.ptype, 'bar')
        plot_property_panel.acceptPanel()
        plot_property_panel.destroy()

        # move up and down

        # cannot move up first item
        plot_dialog.plot_list.setCurrentRow(0)
        plot_dialog.move_up_plot()
        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'violin')
        self.assertEqual(layout_plot.plot_settings[1].plot_type, 'bar')
        # move up second item
        plot_dialog.plot_list.setCurrentRow(1)
        plot_dialog.move_up_plot()
        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'bar')
        self.assertEqual(layout_plot.plot_settings[1].plot_type, 'violin')

        # cannot move down second item
        plot_dialog.plot_list.setCurrentRow(1)
        plot_dialog.move_down_plot()
        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'bar')
        self.assertEqual(layout_plot.plot_settings[1].plot_type, 'violin')
        # move down first item
        plot_dialog.plot_list.setCurrentRow(0)
        plot_dialog.move_down_plot()
        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'violin')
        self.assertEqual(layout_plot.plot_settings[1].plot_type, 'bar')

        self.assertEqual(True, manager.removeLayout(layout))
Exemplo n.º 16
0
    def test_duplicate_chart_in_layout(self):  # pylint: disable=too-many-statements
        """
        Test duplicate charts in layout plot up and down
        """
        print('duplicate charts in layout plot up and down')

        # create project and layout
        project = QgsProject.instance()
        layout = QgsPrintLayout(project)
        layout_name = "PrintLayoutDuplicatePlot"
        layout.initializeDefaults()
        layout.setName(layout_name)
        manager = project.layoutManager()
        self.assertEqual(True, manager.addLayout(layout))
        layout = manager.layoutByName(layout_name)
        layout_plot = PlotLayoutItem(layout)
        self.assertEqual(len(layout_plot.plot_settings), 1)
        # self.assertEqual(len(layout.items()), 0)
        layout.addLayoutItem(layout_plot)
        # self.assertEqual(len(layout.items()), 1)
        plot_dialog = PlotLayoutItemWidget(None, layout_plot)
        self.assertEqual(len(layout_plot.plot_settings), 1)

        # edit first plot
        plot_dialog.setDockMode(True)
        plot_dialog.show_properties()
        plot_property_panel = plot_dialog.panel
        plot_property_panel.set_plot_type('violin')
        self.assertEqual(plot_property_panel.ptype, 'violin')
        plot_property_panel.x_combo.setExpression('mid')
        plot_property_panel.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_FILTER,
            QgsProperty.fromExpression('"mid">20'))
        plot_property_panel.acceptPanel()
        plot_property_panel.destroy()

        # duplicate plot
        plot_dialog.duplicate_plot()
        self.assertEqual(len(layout_plot.plot_settings), 2)

        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'violin')
        self.assertEqual(layout_plot.plot_settings[1].plot_type, 'violin')
        self.assertEqual((layout_plot.plot_settings[0]).properties['x_name'],
                         'mid')
        self.assertEqual((layout_plot.plot_settings[1]).properties['x_name'],
                         'mid')
        self.assertEqual(
            layout_plot.plot_settings[0].data_defined_properties.property(
                PlotSettings.PROPERTY_FILTER),
            QgsProperty.fromExpression('"mid">20'))
        self.assertEqual(
            layout_plot.plot_settings[1].data_defined_properties.property(
                PlotSettings.PROPERTY_FILTER),
            QgsProperty.fromExpression('"mid">20'))

        # edit second plot
        plot_dialog.plot_list.setCurrentRow(1)
        plot_dialog.show_properties()
        plot_property_panel = plot_dialog.panel
        plot_property_panel.set_plot_type('bar')
        self.assertEqual(plot_property_panel.ptype, 'bar')
        plot_property_panel.x_combo.setExpression('qid')
        plot_property_panel.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_FILTER,
            QgsProperty.fromExpression('"qid">20'))
        plot_property_panel.acceptPanel()
        plot_property_panel.destroy()

        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'violin')
        self.assertEqual(layout_plot.plot_settings[1].plot_type, 'bar')
        self.assertEqual((layout_plot.plot_settings[0]).properties['x_name'],
                         'mid')
        self.assertEqual((layout_plot.plot_settings[1]).properties['x_name'],
                         'qid')
        self.assertEqual(
            layout_plot.plot_settings[0].data_defined_properties.property(
                PlotSettings.PROPERTY_FILTER),
            QgsProperty.fromExpression('"mid">20'))
        self.assertEqual(
            layout_plot.plot_settings[1].data_defined_properties.property(
                PlotSettings.PROPERTY_FILTER),
            QgsProperty.fromExpression('"qid">20'))

        # edit first plot
        plot_dialog.plot_list.setCurrentRow(0)
        plot_dialog.show_properties()
        plot_property_panel = plot_dialog.panel
        plot_property_panel.set_plot_type('scatter')
        self.assertEqual(plot_property_panel.ptype, 'scatter')
        plot_property_panel.x_combo.setExpression('uid')
        plot_property_panel.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_FILTER,
            QgsProperty.fromExpression('"uid">20'))
        plot_property_panel.acceptPanel()
        plot_property_panel.destroy()

        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'scatter')
        self.assertEqual(layout_plot.plot_settings[1].plot_type, 'bar')
        self.assertEqual((layout_plot.plot_settings[0]).properties['x_name'],
                         'uid')
        self.assertEqual((layout_plot.plot_settings[1]).properties['x_name'],
                         'qid')
        self.assertEqual(
            layout_plot.plot_settings[0].data_defined_properties.property(
                PlotSettings.PROPERTY_FILTER),
            QgsProperty.fromExpression('"uid">20'))
        self.assertEqual(
            layout_plot.plot_settings[1].data_defined_properties.property(
                PlotSettings.PROPERTY_FILTER),
            QgsProperty.fromExpression('"qid">20'))

        self.assertEqual(True, manager.removeLayout(layout))
    def processAlgorithm(self, parameters, context, feedback):
        """This actually creates the print layout and exporting as .pdf document"""

        log = feedback.setProgressText

        input_title = self.parameterAsString(parameters, self.INPUT_TITLE,
                                             context)
        input_subtitle = self.parameterAsString(parameters,
                                                self.INPUT_SUBTITLE, context)
        input_credit_text = self.parameterAsString(parameters,
                                                   self.INPUT_CREDIT_TEXT,
                                                   context)
        output_pdf_path = self.parameterAsString(parameters,
                                                 self.OUTPUT_PDF_PATH, context)

        log(f"Title: {input_title}")
        log(f"Subtitle: {input_subtitle}")
        log(f"Credit Text: {input_credit_text}")
        log(f"Output pdf path: {output_pdf_path}")

        #This creates a new print layout
        project = context.project()
        manager = project.layoutManager()
        layout = QgsPrintLayout(project)
        layoutName = 'EcoValuator Layout'  #layoutName is going to be name of Title. Change this later

        layouts_list = manager.printLayouts()
        for layout in layouts_list:
            if layout.name() == layoutName:
                manager.removeLayout(layout)

        layout = QgsPrintLayout(project)
        layout.initializeDefaults()  #create default map canvas
        layout.setName(layoutName)
        manager.addLayout(layout)

        #This adds a map item to the Print Layout
        map = QgsLayoutItemMap(layout)
        map.setRect(20, 20, 20, 20)

        #Set Extent
        canvas = iface.mapCanvas()
        map.setExtent(canvas.extent())  #sets map extent to current map canvas
        layout.addLayoutItem(map)

        #Move & Resize
        map.attemptMove(QgsLayoutPoint(5, 27, QgsUnitTypes.LayoutMillimeters))
        map.attemptResize(
            QgsLayoutSize(218, 178, QgsUnitTypes.LayoutMillimeters))

        #Gather visible layers in project layer tree and create a list of the map layer objects
        #Those which are not active (layers_to_remove) will subsequently remove from the legend model
        tree_layers = project.layerTreeRoot().children()
        active_layers = [
            layer.name() for layer in tree_layers if layer.isVisible()
        ]
        layers_to_remove = [
            layer for layer in project.mapLayers().values()
            if layer.name() not in active_layers
        ]

        #This adds a legend item to the Print Layout
        legend = QgsLayoutItemLegend(layout)
        layout.addLayoutItem(legend)
        legend.attemptMove(
            QgsLayoutPoint(219, 5, QgsUnitTypes.LayoutMillimeters))
        #Get reference to existing legend model and root group then remove the unchecked layers
        legend.setAutoUpdateModel(False)  #not sure if this line is required
        model = legend.model()
        group = model.rootGroup()
        for layer in layers_to_remove:
            group.removeLayer(layer)
        legend.adjustBoxSize()

        #This adds labels to the map
        title = QgsLayoutItemLabel(layout)
        title.setText(input_title)
        title.setFont(QFont("Arial", 28))
        title.adjustSizeToText()
        layout.addLayoutItem(title)
        title.attemptMove(QgsLayoutPoint(10, 4,
                                         QgsUnitTypes.LayoutMillimeters))

        subtitle = QgsLayoutItemLabel(layout)
        subtitle.setText(input_subtitle)
        subtitle.setFont(QFont("Arial", 17))
        subtitle.adjustSizeToText()
        layout.addLayoutItem(subtitle)
        subtitle.attemptMove(
            QgsLayoutPoint(11, 20, QgsUnitTypes.LayoutMillimeters))

        credit_text = QgsLayoutItemLabel(layout)
        credit_text.setText(input_credit_text)
        credit_text.setFont(QFont("Arial", 10))
        credit_text.adjustSizeToText()
        layout.addLayoutItem(credit_text)
        credit_text.attemptMove(
            QgsLayoutPoint(219, 190, QgsUnitTypes.LayoutMillimeters))

        #this creates credit text (line1) in bottom right corner of map layout giving credit to Key-Log Economics
        keylog_credits1 = QgsLayoutItemLabel(layout)
        keylog_credits1.setText("Created using EcoValuator Plugin")
        keylog_credits1.setFont(QFont("Arial", 10))
        keylog_credits1.adjustSizeToText()
        layout.addLayoutItem(keylog_credits1)
        keylog_credits1.attemptMove(
            QgsLayoutPoint(219, 195, QgsUnitTypes.LayoutMillimeters))

        #this creates credit text (line2) in bottom right corner of map layout giving credit to Key-Log Economics
        keylog_credits2 = QgsLayoutItemLabel(layout)
        keylog_credits2.setText("by Key-Log Economics")
        keylog_credits2.setFont(QFont("Arial", 10))
        keylog_credits2.adjustSizeToText()
        layout.addLayoutItem(keylog_credits2)
        keylog_credits2.attemptMove(
            QgsLayoutPoint(219, 200, QgsUnitTypes.LayoutMillimeters))

        #This exports a Print Layout as an image
        manager = QgsProject.instance().layoutManager(
        )  #this is a reference to the layout Manager, which contains a list of print layouts

        layout = manager.layoutByName(
            layoutName
        )  #this accesses a specific layout, by name (which is a string)

        exporter = QgsLayoutExporter(
            layout)  #this creates a QgsLayoutExporter object
        exporter.exportToPdf(output_pdf_path,
                             QgsLayoutExporter.PdfExportSettings())

        log("Done!")

        result = {
        }  #The processAlgorithm wants to return a dictionary. We don't actually need to do this so instead we return an empty one
        return result
Exemplo n.º 18
0
    def testSymbolExpressionRender(self):
        """Test expressions embedded in legend node text"""
        point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
        point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
        layout = QgsPrintLayout(QgsProject.instance())
        layout.setName('LAYOUT')
        layout.initializeDefaults()

        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
        map.setFrameEnabled(True)
        map.setLayers([point_layer])
        layout.addLayoutItem(map)
        map.setExtent(point_layer.extent())

        legend = QgsLayoutItemLegend(layout)
        legend.setTitle("Legend")
        legend.attemptSetSceneRect(QRectF(120, 20, 100, 100))
        legend.setFrameEnabled(True)
        legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle('')
        legend.setLegendFilterByMapEnabled(False)
        legend.setStyleFont(QgsLegendStyle.Title,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Group,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Subgroup,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Symbol,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.SymbolLabel,
                            QgsFontUtils.getStandardTestFont('Bold', 16))

        legend.setAutoUpdateModel(False)

        QgsProject.instance().addMapLayers([point_layer])
        s = QgsMapSettings()
        s.setLayers([point_layer])

        group = legend.model().rootGroup().addGroup(
            "Group [% 1 + 5 %] [% @layout_name %]")
        layer_tree_layer = group.addLayer(point_layer)
        counterTask = point_layer.countSymbolFeatures()
        counterTask.waitForFinished()  # does this even work?
        layer_tree_layer.setCustomProperty(
            "legend/title-label",
            'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')
        QgsMapLayerLegendUtils.setLegendNodeUserLabel(layer_tree_layer, 0,
                                                      'xxxx')
        legend.model().refreshLayerLegend(layer_tree_layer)
        layer_tree_layer.setLabelExpression(
            'Concat(@symbol_id, @symbol_label, count("Class"))')
        legend.model().layerLegendNodes(layer_tree_layer)[0].setUserLabel(
            ' sym 1')
        legend.model().layerLegendNodes(layer_tree_layer)[1].setUserLabel(
            '[%@symbol_count %]')
        legend.model().layerLegendNodes(layer_tree_layer)[2].setUserLabel(
            '[% count("Class") %]')
        layout.addLayoutItem(legend)
        legend.setLinkedMap(map)
        legend.updateLegend()
        print(layer_tree_layer.labelExpression())
        TM = QgsApplication.taskManager()
        actask = TM.activeTasks()
        print(TM.tasks(), actask)
        count = actask[0]
        count.waitForFinished()
        map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))
        checker = QgsLayoutChecker('composer_legend_symbol_expression', layout)
        checker.setControlPathPrefix("composer_legend")
        sleep(4)
        result, message = checker.testLayout()
        self.assertTrue(result, message)

        QgsProject.instance().removeMapLayers([point_layer.id()])
Exemplo n.º 19
0
    def testProxyModel(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        model = QgsLayoutManagerModel(manager)
        proxy = QgsLayoutManagerProxyModel()
        proxy.setSourceModel(model)
        self.assertEqual(proxy.rowCount(QModelIndex()), 0)
        self.assertEqual(
            proxy.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            proxy.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)

        layout = QgsPrintLayout(project)
        layout.setName('ccc')
        self.assertTrue(manager.addLayout(layout))

        self.assertEqual(proxy.rowCount(QModelIndex()), 1)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'ccc')
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)

        layout2 = QgsPrintLayout(project)
        layout2.setName('bbb')
        self.assertTrue(manager.addLayout(layout2))
        self.assertEqual(proxy.rowCount(QModelIndex()), 2)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'bbb')
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'ccc')
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)

        layout.setName('aaa')
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'aaa')
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'bbb')
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)

        model.setAllowEmptyLayout(True)
        self.assertEqual(proxy.rowCount(QModelIndex()), 3)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'aaa')
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            proxy.data(proxy.index(2, 0, QModelIndex()), Qt.DisplayRole),
            'bbb')
        self.assertEqual(
            proxy.data(proxy.index(2, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)

        r = QgsReport(project)
        r.setName('ddd')
        manager.addLayout(r)
        self.assertEqual(proxy.rowCount(QModelIndex()), 4)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'aaa')
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            proxy.data(proxy.index(2, 0, QModelIndex()), Qt.DisplayRole),
            'bbb')
        self.assertEqual(
            proxy.data(proxy.index(2, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(
            proxy.data(proxy.index(3, 0, QModelIndex()), Qt.DisplayRole),
            'ddd')
        self.assertEqual(
            proxy.data(proxy.index(3, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), r)

        proxy.setFilters(QgsLayoutManagerProxyModel.FilterPrintLayouts)
        self.assertEqual(proxy.filters(),
                         QgsLayoutManagerProxyModel.FilterPrintLayouts)
        self.assertEqual(proxy.rowCount(QModelIndex()), 3)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'aaa')
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            proxy.data(proxy.index(2, 0, QModelIndex()), Qt.DisplayRole),
            'bbb')
        self.assertEqual(
            proxy.data(proxy.index(2, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)

        proxy.setFilters(QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(proxy.filters(),
                         QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(proxy.rowCount(QModelIndex()), 2)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            proxy.data(proxy.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'ddd')
        self.assertEqual(
            proxy.data(proxy.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), r)

        proxy.setFilters(QgsLayoutManagerProxyModel.FilterPrintLayouts
                         | QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(
            proxy.filters(), QgsLayoutManagerProxyModel.FilterPrintLayouts
            | QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(proxy.rowCount(QModelIndex()), 4)
Exemplo n.º 20
0
    def createLayout(self):
        print(u'createLayout()')

        templateFile = self.createLayoutDialog.comboBoxTemplate.currentText()
        templateQpt = os.path.join(self.dataPath, templateFile)

        layoutName = self.createLayoutDialog.lineEditName.text()

        project = QgsProject.instance()
        layoutManager = project.layoutManager()

        oldLayout = layoutManager.layoutByName(layoutName)
        if oldLayout is not None:
            print(u'removing: {}'.format(oldLayout))
            layoutManager.removeLayout(oldLayout)

        # create new layout
        layout = QgsPrintLayout(project)

        # load layout template
        fl = QFile(templateQpt)
        doc = QDomDocument()
        doc.setContent(fl)
        layout.loadFromTemplate(doc, QgsReadWriteContext())

        # set name
        layout.setName(layoutName)

        # set map properties
        map = self.getItemById(layout, u'RC_map')
        if map is not None:
            #print(map.crs().description())
            map.zoomToExtent(self.iface.mapCanvas().extent())

        # set default label values
        for configurationItem in simsLayoutConfiguration:
            label = self.getItemById(layout, configurationItem['code'])
            if label is not None and isinstance(label, QgsLayoutItemLabel):
                if configurationItem['default'] is not None:
                    label.setText(configurationItem['default'])

        # set overview map
        map = self.getItemById(layout, u'RC_overview')
        if map is not None:
            worldLayer = self.addWorldLayer()
            map.setFollowVisibilityPreset(False)
            map.setKeepLayerSet(True)
            map.setLayers([worldLayer])

            overviewCrs = QgsCoordinateReferenceSystem("EPSG:54030")
            map.setCrs(overviewCrs)

            extent = worldLayer.extent()
            layerCrs = worldLayer.sourceCrs()
            if not layerCrs == overviewCrs:
                transform = QgsCoordinateTransform(layerCrs, overviewCrs,
                                                   QgsProject.instance())
                extent = transform.transformBoundingBox(extent)
            map.zoomToExtent(extent)

            root = QgsProject.instance().layerTreeRoot()
            rl = root.findLayer(worldLayer.id())
            rl.setItemVisibilityChecked(False)

        # set disclamer
        languageChoice = self.createLayoutDialog.comboBoxLanguage.currentText()

        label = self.getItemById(layout, u'RC_disclaimer')
        if label is not None:
            label.setText(simsDisclamers[languageChoice])

        label = self.getItemById(layout, u'RC_logotext')
        if label is not None:
            label.setText(simsLogoTexts[languageChoice])

        # set title
        label = self.getItemById(layout, u'RC_title')
        if label is not None:
            label.setText(self.createLayoutDialog.lineEditName.text())

        # set Copyright
        # possibly dynamically: [%'© SIMS '  || year(now())%]
        '''
        label = self.getItemById(layout, u'COPYRIGHT')
        if label is not None:
            print(label)
            label.setText(u'© SIMS {0}'.format(datetime.now().year))

        # set filename
        label = self.getItemById(layout, u'FILENAME')
        if label is not None:
            print(label)
            filename = QgsProject.instance().fileName()
            if filename == u'':
                filename = u'filename unknown, project not saved'
            label.setText(filename)
        '''

        # set NS logo
        picture = self.getItemById(layout, u'RC_logo1')
        if picture is not None:
            logoChoice = self.createLayoutDialog.comboBoxNsLogo.currentText()
            logoSvg = os.path.join(self.dataPath, u'logos', logoChoice)
            picture.setPicturePath(logoSvg)

        # set IFRC logo
        picture = self.getItemById(layout, u'RC_logo2')
        if picture is not None:
            logo = simsIfrcLogos[languageChoice]
            logoSvg = os.path.join(self.dataPath, u'img', logo)
            picture.setPicturePath(logoSvg)

        # set date
        label = self.getItemById(layout, u'RC_date')
        if label is not None:
            now = datetime.now()
            month = simsMonths[languageChoice][now.month]
            label.setText(now.strftime('%d {} %Y').format(month))

        # set North Arrow
        picture = self.getItemById(layout, u'RC_northarrow')
        if picture is not None:
            logoSvg = os.path.join(QgsApplication.pkgDataPath(), u'svg',
                                   u'arrows', u'NorthArrow_02.svg')
            picture.setPicturePath(logoSvg)

        # clear default label values

        # add to project and open designer window
        layoutManager.addLayout(layout)
        designer = self.iface.openLayoutDesigner(layout)
Exemplo n.º 21
0
class ScangisAtlas:
    def __init__(self, iface):
        self.iface = iface
        self.virtualLayerName = u'deelnemers_atlas'
        self.layoutName = u'Scangis Atlas'

        #print(__file__)
        self.pluginDir = os.path.dirname(__file__)
        #print(self.pluginDir)
        self.templateFile = os.path.join(self.pluginDir, u'data', u'a4.qpt')
        self.scangisStyle = os.path.join(self.pluginDir, u'data',
                                         u'pakketten_atlas_alz.qml')
        #print(self.templateFile)

    def initGui(self):
        self.action = QAction(u'Scangis Atlas', self.iface.mainWindow())
        self.action.triggered.connect(self.run)
        self.iface.addToolBarIcon(self.action)

    def unload(self):
        self.iface.removeToolBarIcon(self.action)
        del self.action

    def run(self):
        project = QgsProject.instance()

        # set qml
        scangisLayer = self.iface.activeLayer()
        #print(scangisLayer.name())
        scangisLayer.loadNamedStyle(self.scangisStyle)

        # delete existing deelnemers virtual layer
        oldLayers = project.mapLayersByName(self.virtualLayerName)
        for oldLayer in oldLayers:
            project.removeMapLayer(oldLayer.id())

        # create new virtual layer
        query = u'?query=SELECT min(ID) AS ID, DEELN_NAAM, st_union(geometry) AS geometry FROM "{}" GROUP BY DEELN_NAAM'.format(
            scangisLayer.name())
        virtualLayer = QgsVectorLayer(query, self.virtualLayerName, "virtual")
        project.addMapLayer(virtualLayer)

        ltr = QgsProject.instance().layerTreeRoot()
        rootLayer = ltr.findLayer(virtualLayer.id())
        rootLayer.setItemVisibilityChecked(False)

        self.iface.mapCanvas().refreshAllLayers()

        # delete existing atlas layout
        layoutManager = project.layoutManager()
        #print(layoutManager)
        #print(layoutManager.layouts())
        oldLayout = layoutManager.layoutByName(self.layoutName)
        if oldLayout is not None:
            layoutManager.removeLayout(oldLayout)

        # create new layout
        self.atlasLayout = QgsPrintLayout(project)

        # load layout template
        fl = QFile(self.templateFile)
        doc = QDomDocument()
        doc.setContent(fl)
        rw_context = QgsReadWriteContext()
        rw_context.setPathResolver(project.pathResolver())
        self.atlasLayout.loadFromTemplate(doc, rw_context)

        # set name
        self.atlasLayout.setName(self.layoutName)

        # add to project
        layoutManager.addLayout(self.atlasLayout)

        # turn on atlas
        atl = self.atlasLayout.atlas()
        atl.setEnabled(True)
        atl.setCoverageLayer(virtualLayer)
        atl.setHideCoverage(True)
        itemId = u'map1'
        item = self.getLayoutItem(itemId, QgsLayoutItemMap)
        item.setAtlasDriven(True)

        # set title
        itemId = u'label_title'
        item = self.getLayoutItem(itemId, QgsLayoutItemLabel)
        #item.setText(u'[% attribute(@atlas_feature, \'DEELN_NAAM\') %]')
        item.setText(u'[% "DEELN_NAAM" %]')

        # set source info
        itemId = u'label_source'
        item = self.getLayoutItem(itemId, QgsLayoutItemLabel)
        exp = u"[% format_date(now(), 'dd-MM-yyyy (hh:mm:ss)') || '\\n' || 'pagina ' || @atlas_featurenumber || '/' ||  @atlas_totalfeatures %]"
        item.setText(exp)
        item.setHAlign(2)  # right
        item.setVAlign(64)  # bottom

        # set legend filter
        itemId = u'legend1'
        item = self.getLayoutItem(itemId, QgsLayoutItemLegend)
        #print(item)
        item.setLegendFilterByMapEnabled(True)

        #QMessageBox.information(None, u'Scangis Atlas', u'Atlas finished! :)')
        designer = self.iface.openLayoutDesigner(self.atlasLayout)

        # new in qgis 3.3
        if qgis.utils.Qgis.QGIS_VERSION_INT >= 30300:
            designer.setAtlasPreviewEnabled(True)

    def getLayoutItem(self, itemId, itemType):
        item = self.atlasLayout.itemById(itemId)
        if item is None:
            #print(u'Layout does not contain item: \'{0}\''.format(itemId))
            return None
        if not type(item) == u'qgis._core.{0}'.format(itemType.__name__):
            item = sip.cast(item, itemType)
        return item
Exemplo n.º 22
0
    def testExpressionInText(self):
        """Test expressions embedded in legend node text"""

        point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
        point_layer = QgsVectorLayer(point_path, 'points', 'ogr')

        layout = QgsPrintLayout(QgsProject.instance())
        layout.setName('LAYOUT')
        layout.initializeDefaults()

        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
        map.setFrameEnabled(True)
        map.setLayers([point_layer])
        layout.addLayoutItem(map)
        map.setExtent(point_layer.extent())

        legend = QgsLayoutItemLegend(layout)
        legend.setTitle("Legend")
        legend.attemptSetSceneRect(QRectF(120, 20, 100, 100))
        legend.setFrameEnabled(True)
        legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle('')
        legend.setLegendFilterByMapEnabled(False)
        legend.setStyleFont(QgsLegendStyle.Title,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Group,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Subgroup,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.Symbol,
                            QgsFontUtils.getStandardTestFont('Bold', 16))
        legend.setStyleFont(QgsLegendStyle.SymbolLabel,
                            QgsFontUtils.getStandardTestFont('Bold', 16))

        legend.setAutoUpdateModel(False)

        QgsProject.instance().addMapLayers([point_layer])
        s = QgsMapSettings()
        s.setLayers([point_layer])

        group = legend.model().rootGroup().addGroup(
            "Group [% 1 + 5 %] [% @layout_name %]")
        layer_tree_layer = group.addLayer(point_layer)
        layer_tree_layer.setCustomProperty(
            "legend/title-label",
            'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')
        QgsMapLayerLegendUtils.setLegendNodeUserLabel(layer_tree_layer, 0,
                                                      'xxxx')
        legend.model().refreshLayerLegend(layer_tree_layer)
        legend.model().layerLegendNodes(layer_tree_layer)[0].setUserLabel(
            'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')

        layout.addLayoutItem(legend)
        legend.setLinkedMap(map)

        map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))

        checker = QgsLayoutChecker('composer_legend_expressions', layout)
        checker.setControlPathPrefix("composer_legend")
        result, message = checker.testLayout()
        self.assertTrue(result, message)

        QgsProject.instance().removeMapLayers([point_layer.id()])
Exemplo n.º 23
0
    def testReadWriteXml(self):
        p = QgsProject()
        l = QgsPrintLayout(p)
        l.setName('my layout')
        l.setUnits(QgsUnitTypes.LayoutInches)
        collection = l.pageCollection()

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A6')
        collection.addPage(page)

        grid = l.gridSettings()
        grid.setResolution(QgsLayoutMeasurement(5, QgsUnitTypes.LayoutPoints))

        g1 = QgsLayoutGuide(
            Qt.Horizontal,
            QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters),
            l.pageCollection().page(0))
        l.guides().addGuide(g1)

        snapper = l.snapper()
        snapper.setSnapTolerance(7)

        # add some items
        item1 = QgsLayoutItemMap(l)
        item1.setId('xxyyxx')
        l.addItem(item1)
        item2 = QgsLayoutItemMap(l)
        item2.setId('zzyyzz')
        l.addItem(item2)

        l.setReferenceMap(item2)

        doc = QDomDocument("testdoc")
        elem = l.writeXml(doc, QgsReadWriteContext())

        l2 = QgsPrintLayout(p)
        self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext()))
        self.assertEqual(l2.name(), 'my layout')
        self.assertEqual(l2.units(), QgsUnitTypes.LayoutInches)

        collection2 = l2.pageCollection()
        self.assertEqual(collection2.pageCount(), 1)
        self.assertAlmostEqual(collection2.page(0).pageSize().width(), 105, 4)
        self.assertEqual(collection2.page(0).pageSize().height(), 148)
        self.assertEqual(l2.gridSettings().resolution().length(), 5.0)
        self.assertEqual(l2.gridSettings().resolution().units(),
                         QgsUnitTypes.LayoutPoints)
        self.assertEqual(l2.guides().guidesOnPage(0)[0].orientation(),
                         Qt.Horizontal)
        self.assertEqual(l2.guides().guidesOnPage(0)[0].position().length(),
                         5.0)
        self.assertEqual(l2.guides().guidesOnPage(0)[0].position().units(),
                         QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(l2.snapper().snapTolerance(), 7)

        # check restored items
        new_item1 = l2.itemByUuid(item1.uuid())
        self.assertTrue(new_item1)
        self.assertEqual(new_item1.id(), 'xxyyxx')
        new_item2 = l2.itemByUuid(item2.uuid())
        self.assertTrue(new_item2)
        self.assertEqual(new_item2.id(), 'zzyyzz')
        self.assertEqual(l2.referenceMap().id(), 'zzyyzz')
Exemplo n.º 24
0
    def testModel(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        model = QgsLayoutManagerModel(manager)
        self.assertEqual(model.rowCount(QModelIndex()), 0)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)
        self.assertEqual(model.indexFromLayout(None), QModelIndex())

        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        self.assertEqual(model.indexFromLayout(layout), QModelIndex())
        self.assertTrue(manager.addLayout(layout))

        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), 'test layout')
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), layout)
        self.assertEqual(model.indexFromLayout(layout), model.index(0, 0, QModelIndex()))
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.layoutFromIndex(model.index(1, 0, QModelIndex())), None)

        layout.setName('test Layout')
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), 'test Layout')

        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        self.assertTrue(manager.addLayout(layout2))

        self.assertEqual(model.rowCount(QModelIndex()), 2)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), 'test Layout')
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), layout)
        self.assertEqual(model.indexFromLayout(layout), model.index(0, 0, QModelIndex()))
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole), 'test layout2')
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(model.layoutFromIndex(model.index(1, 0, QModelIndex())), layout2)
        self.assertEqual(model.indexFromLayout(layout2), model.index(1, 0, QModelIndex()))

        manager.removeLayout(layout)
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), 'test layout2')
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), layout2)
        self.assertEqual(model.layoutFromIndex(model.index(1, 0, QModelIndex())), None)
        self.assertEqual(model.indexFromLayout(layout2), model.index(0, 0, QModelIndex()))

        manager.clear()
        self.assertEqual(model.rowCount(QModelIndex()), 0)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)

        # with empty row
        model.setAllowEmptyLayout(True)
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)

        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        self.assertTrue(manager.addLayout(layout))
        self.assertEqual(model.rowCount(QModelIndex()), 2)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole), 'test layout')
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(model.data(model.index(2, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(2, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)
        self.assertEqual(model.layoutFromIndex(model.index(1, 0, QModelIndex())), layout)
        self.assertEqual(model.indexFromLayout(layout), model.index(1, 0, QModelIndex()))

        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        self.assertTrue(manager.addLayout(layout2))
        self.assertEqual(model.rowCount(QModelIndex()), 3)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole), 'test layout')
        self.assertEqual(model.data(model.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(model.data(model.index(2, 0, QModelIndex()), Qt.DisplayRole), 'test layout2')
        self.assertEqual(model.data(model.index(2, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)
        self.assertEqual(model.layoutFromIndex(model.index(1, 0, QModelIndex())), layout)
        self.assertEqual(model.layoutFromIndex(model.index(2, 0, QModelIndex())), layout2)
        self.assertEqual(model.indexFromLayout(layout), model.index(1, 0, QModelIndex()))
        self.assertEqual(model.indexFromLayout(layout2), model.index(2, 0, QModelIndex()))

        manager.clear()
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(model.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)
Exemplo n.º 25
0
class run(QObject):
    def __init__(self, id, gtotool, config, debug):
        super(run, self).__init__()
        try:
            self.debug = debug
            self.gtotool=gtotool
            self.gtomain = gtotool.gtomain
            self.info =gtotool.info
            self.metadata = self.gtomain.metadata
            templatedir = self.metadata.dirPrintLayouts
            self.iface = self.gtomain.iface
            #tool data
            template = config.get('template',None)
            activetool= config.get('active_tool',None)
            scale = config.get('scale',0)
            #init
            templatefile = None
            layoutname =config.get('layoutname', None)
            if template and layoutname is None:
                layoutname= os.path.splitext(template)[0]#default layoutname for template
            if self.debug:self.info.log("layoutname:",layoutname)
            prj = QgsProject.instance()
            projectLayoutManager = prj.layoutManager()#QgsLayoutManager
            self.layout = None
            if template is not None:
                templatefile = os.path.join(templatedir , template)
                if debug: self.info.log("template:",templatefile)
                if os.path.isfile(templatefile):
                    f= open(templatefile, 'r')
                    templateContent = f.read()
                    f.close()
                    doc=QDomDocument()
                    doc.setContent(templateContent)
                    pr = QgsPathResolver(templatefile)
                    rwc = QgsReadWriteContext()
                    rwc.setPathResolver(pr)
                    self.layout = QgsPrintLayout(prj)
                    self.layout.loadFromTemplate(doc,rwc)
                    self.layout.setName(layoutname)
                    projectLayoutManager.addLayout(self.layout)
            self.layout = projectLayoutManager.layoutByName(layoutname)
            if self.debug: self.info.log(type(self.layout))
            if self.debug and self.layout:self.info.log("found layout:",self.layout.name())
            if self.layout:
                result = self.iface.openLayoutDesigner(self.layout)#QgsLayoutDesignerInterface

                self.layoutview = result.view()#QgsLayoutView
                currenttool = self.layoutview.tool()#QgsLayoutViewTool
                if self.debug: self.info.log(currenttool.toolName())

                if activetool:
                    tool = QgsLayoutViewToolMoveItemContent(self.layoutview)
                    self.layoutview.setTool(tool)

                #itemMap = QgsLayoutItemMap(self.layout)
                referencemap = self.layout.referenceMap()
                referencemap.zoomToExtent(self.iface.mapCanvas().extent())
                if scale < 0:
                    referencemap.setScale(self.iface.mapCanvas().scale())
                elif scale > 0:
                    referencemap.setScale(scale)
                referencemap.refresh()

                if activetool:
                    menu = result.editMenu()
                    for a in menu.actions():
                        if a.objectName() == activetool:
                            if self.debug: self.info.log("set active tool:",activetool)
                            a.trigger()
                            break
                self.result = True
            else:
                self.result="Layout <%s> not found!" % layoutname
        except Exception as e:
            self.info.err(e)
Exemplo n.º 26
0
    def test_read_write_project_with_layout(self):
        """
        Test saving/restoring dialog state of layout plot in project
        """
        # print('read write project with layout test')

        # create project and layout
        project = QgsProject.instance()
        layout = QgsPrintLayout(project)
        layout_name = "PrintLayoutReadWrite"
        layout.initializeDefaults()
        layout.setName(layout_name)
        layout_plot = PlotLayoutItem(layout)
        layout_plot.setId('plot_item')
        plot_item_id = layout_plot.id()
        self.assertEqual(len(layout_plot.plot_settings), 1)
        # self.assertEqual(len(layout.items()), 0)
        layout.addLayoutItem(layout_plot)
        # self.assertEqual(len(layout.items()), 1)
        plot_dialog = PlotLayoutItemWidget(None, layout_plot)

        # add second plot
        plot_dialog.add_plot()
        self.assertEqual(len(layout_plot.plot_settings), 2)

        # edit first plot
        plot_dialog.setDockMode(True)
        plot_dialog.show_properties()
        plot_property_panel = plot_dialog.panel
        plot_property_panel.set_plot_type('violin')
        self.assertEqual(plot_property_panel.ptype, 'violin')
        plot_property_panel.acceptPanel()
        plot_property_panel.destroy()

        # edit second plot
        plot_dialog.plot_list.setCurrentRow(1)
        plot_dialog.show_properties()
        plot_property_panel = plot_dialog.panel
        plot_property_panel.set_plot_type('bar')
        self.assertEqual(plot_property_panel.ptype, 'bar')
        plot_property_panel.acceptPanel()
        plot_property_panel.destroy()

        # write xml

        xml_doc = QDomDocument('layout')
        element = layout.writeXml(xml_doc, QgsReadWriteContext())

        layout_plot.remove_plot(0)
        self.assertEqual(len(layout_plot.plot_settings), 1)
        self.assertEqual(layout_plot.plot_settings[0].plot_type, 'bar')

        layout_plot.remove_plot(0)
        self.assertEqual(len(layout_plot.plot_settings), 0)

        # read xml
        layout2 = QgsPrintLayout(project)
        self.assertTrue(
            layout2.readXml(element, xml_doc, QgsReadWriteContext()))
        layout_plot2 = layout2.itemById(plot_item_id)
        self.assertTrue(layout_plot2)

        self.assertEqual(len(layout_plot2.plot_settings), 2)
        self.assertEqual(layout_plot2.plot_settings[0].plot_type, 'violin')
        self.assertEqual(layout_plot2.plot_settings[1].plot_type, 'bar')
Exemplo n.º 27
0
 def _load_print_layout(self, layer_name, prod_id, dt=None):
     
     window_title = "Print"    # will be checked with a found composer title
     
     """
     Avoid creating a new PrintComposer again and again here.
     Otherwise more and more composers will be added to the list - even with the same name.
     """
     
     project = QgsProject.instance()
     # From it, you can get the current layoutManager instance and deduce the layouts
     layout_manager = project.layoutManager()
     
     layout = layout_manager.layoutByName(window_title)
     
     if not layout:
         self.out("no composer found; creating one...")
         
         # Load the template into the composer
         # QGIS 2:
         #active_composer = self.iface.createNewComposer(window_title)    #createNewComposer()
         #active_composer = QgsComposition(QgsProject.instance())
         
         #layout = QgsLayout(project)
         layout = QgsPrintLayout(project)
         layout.initializeDefaults()    # initializes default settings for blank print layout canvas
         
         
         q_xmldoc = self._create_qdocument_from_print_template_content()
         
         # load layout from template and add to Layout Manager
         #layout.composition().loadFromTemplate(q_xmldoc)    # QGIS 2
         layout.loadFromTemplate(q_xmldoc, QgsReadWriteContext())
         layout.setName(window_title)
         
         layout_manager.addLayout(layout)
         
         
         # Update Logo:
         
         #logo_item = layout.getComposerItemById('logo')    # QGIS 2
         logo_item = layout.itemById('logo')
         #self.out(">>> logo_item: '{}'".format(logo_item))    # gibt nur die Objekt-ID aus
         logo_image = self._model.logo_path
         self.out("Logo: {}".format(logo_image))
         if logo_image.exists():
             logo_item.setPicturePath(str(logo_image))
         else:
             self.out("  ERROR: logo '{}' not found!".format(logo_image), False)
     # if
     
     
     """
     Hier versuche ich ein für die Überschrift mit einer ID ('headline') versehenes
     QgsLabel aus dem Template ausfindig zu machen. Ich mache das hier sehr kompliziert,
     es gibt bestimmt einen einfacheren Weg.
     Folgendes hat NICHT funktioniert:
     map_item = active_composer.getComposerItemById('headline')
     print(active_composer.items())
     liefert: [<PyQt4.QtGui.QGraphicsRectItem object at 0x124c60e8>, <qgis._core.QgsComposerLabel object at 0x124c65a8>, ... ]
     """
     
     ''' other possibility:
     for item in list(layout.items()):
         #if type(item) != QgsComposerLabel:
     '''
     
     # QgsComposerLabel:
     composer_label = layout.itemById('headline')    # a QgsComposerLabel was provided with the ID 'headline' in the template
     # -> None if not found
     
     if composer_label:
         title    = self._model.title(prod_id, dt)
         subtitle = ""
         if prod_id != 'RW':
             subtitle = "\n{}-Produkt (Basis: RW)".format(prod_id)
         
         composer_label.setText(title + subtitle)
     else:
         # A note that the template needs to be revised:
         self.out("no element with id 'headline' found!", False)
     
     
     
     legend = layout.itemById('legend')
     
     if not legend:
         self.out("legend couldn't created!", False)
         return
     
     
     #
     # Layer für die Legende ausfindig machen
     #
     
     # You would just need to make sure your layer has a name you can distinguish from others. Instead of:
     # Vorherige Version:
     #active_raster_layer = self.iface.activeLayer()
     
     # do:
     l_layer = project.mapLayersByName(layer_name)
     
     if not l_layer:
         self.out("legend: no layer found with name '{}'!".format(layer_name), False)
         return
     
     active_raster_layer = l_layer[0]
     
     #print("Legend active_raster_layer id:",   active_raster_layer.id())     # ok
     #print("Legend active_raster_layer name:", active_raster_layer.name())   # ok
     #legend.model().setLayerSet([layer.id() for layer in layers])
     #legend.model().setLayerSet([active_raster_layer.id()])    # bringt nichts
     # DAS ist es! Dies fügt zumindest erstmal das interessierende Rasterlayer hinzu:
     #legend.modelV2().rootGroup().addLayer(active_raster_layer)
     #legend.updateLegend()
     
     #for layout in layout_manager.printLayouts():    # iterate layouts
     
     ''' would be ok, if we want to create a new legend -> then legend appears at the upper left corner
     legend = QgsLayoutItemLegend(layout)
     #legend.setTitle('Legend')
     legend.setAutoUpdateModel(False)
     group = legend.model().rootGroup()
     group.clear()
     group.addLayer(active_raster_layer)
     layout.addItem(legend)
     legend.adjustBoxSize()
     #legend.refresh()    # avoids adding all other layers 
     '''
     
     # uses existing legend object (see above), so we preserve it's layout position:
     legend.setAutoUpdateModel(False)
     group = legend.model().rootGroup()
     group.clear()
     group.addLayer(active_raster_layer)
     legend.adjustBoxSize()
     
     """ By default the newly created composer items have zero position (top left corner of the page) and zero size.
     The position and size are always measured in millimeters.
     # set label 1cm from the top and 2cm from the left of the page
     composerLabel.setItemPosition(20, 10)
     # set both label’s position and size (width 10cm, height 3cm)
     composerLabel.setItemPosition(20, 10, 100, 30)
     A frame is drawn around each item by default. How to remove the frame:
     composerLabel.setFrame(False)
     """
     #print(active_composer.rect().width(), active_composer.rect().height())                   # 1054 911
     #print(self.iface.mapCanvas().size().width(), self.iface.mapCanvas().size().height())     # 1517 535
     # "Leinwandgröße": habe keine vernünftigen Werte oben ermittelt (vielleicht Pixel; ich brauche mm).
     # selbst, mittels Mauszeiger ermittelt:
     width  = 210
     height = 297
     # Rand neben der Legende (mm):
     dw = 10
     dh = 14
     
     """
Exemplo n.º 28
0
    def testProxyModel(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        model = QgsLayoutManagerModel(manager)
        proxy = QgsLayoutManagerProxyModel()
        proxy.setSourceModel(model)
        self.assertEqual(proxy.rowCount(QModelIndex()), 0)
        self.assertEqual(proxy.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(proxy.data(model.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)

        layout = QgsPrintLayout(project)
        layout.setName('ccc')
        self.assertTrue(manager.addLayout(layout))

        self.assertEqual(proxy.rowCount(QModelIndex()), 1)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), 'ccc')
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)

        layout2 = QgsPrintLayout(project)
        layout2.setName('bbb')
        self.assertTrue(manager.addLayout(layout2))
        self.assertEqual(proxy.rowCount(QModelIndex()), 2)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), 'bbb')
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), 'ccc')
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)

        layout.setName('aaa')
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), 'aaa')
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), 'bbb')
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)

        model.setAllowEmptyLayout(True)
        self.assertEqual(proxy.rowCount(QModelIndex()), 3)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), 'aaa')
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(proxy.data(proxy.index(2, 0, QModelIndex()), Qt.DisplayRole), 'bbb')
        self.assertEqual(proxy.data(proxy.index(2, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)

        r = QgsReport(project)
        r.setName('ddd')
        manager.addLayout(r)
        self.assertEqual(proxy.rowCount(QModelIndex()), 4)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), 'aaa')
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(proxy.data(proxy.index(2, 0, QModelIndex()), Qt.DisplayRole), 'bbb')
        self.assertEqual(proxy.data(proxy.index(2, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(proxy.data(proxy.index(3, 0, QModelIndex()), Qt.DisplayRole), 'ddd')
        self.assertEqual(proxy.data(proxy.index(3, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), r)

        proxy.setFilters(QgsLayoutManagerProxyModel.FilterPrintLayouts)
        self.assertEqual(proxy.filters(), QgsLayoutManagerProxyModel.FilterPrintLayouts)
        self.assertEqual(proxy.rowCount(QModelIndex()), 3)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), 'aaa')
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(proxy.data(proxy.index(2, 0, QModelIndex()), Qt.DisplayRole), 'bbb')
        self.assertEqual(proxy.data(proxy.index(2, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), layout2)

        proxy.setFilters(QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(proxy.filters(), QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(proxy.rowCount(QModelIndex()), 2)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(proxy.data(proxy.index(0, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), Qt.DisplayRole), 'ddd')
        self.assertEqual(proxy.data(proxy.index(1, 0, QModelIndex()), QgsLayoutManagerModel.LayoutRole), r)

        proxy.setFilters(QgsLayoutManagerProxyModel.FilterPrintLayouts | QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(proxy.filters(), QgsLayoutManagerProxyModel.FilterPrintLayouts | QgsLayoutManagerProxyModel.FilterReports)
        self.assertEqual(proxy.rowCount(QModelIndex()), 4)
Exemplo n.º 29
0
    def testModel(self):
        project = QgsProject()
        manager = QgsLayoutManager(project)
        model = QgsLayoutManagerModel(manager)
        self.assertEqual(model.rowCount(QModelIndex()), 0)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)
        self.assertEqual(model.indexFromLayout(None), QModelIndex())

        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        self.assertEqual(model.indexFromLayout(layout), QModelIndex())
        self.assertTrue(manager.addLayout(layout))

        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'test layout')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), layout)
        self.assertEqual(model.indexFromLayout(layout),
                         model.index(0, 0, QModelIndex()))
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(1, 0, QModelIndex())), None)

        layout.setName('test Layout')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'test Layout')

        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        self.assertTrue(manager.addLayout(layout2))

        self.assertEqual(model.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'test Layout')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), layout)
        self.assertEqual(model.indexFromLayout(layout),
                         model.index(0, 0, QModelIndex()))
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'test layout2')
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(
            model.layoutFromIndex(model.index(1, 0, QModelIndex())), layout2)
        self.assertEqual(model.indexFromLayout(layout2),
                         model.index(1, 0, QModelIndex()))

        manager.removeLayout(layout)
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'test layout2')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), layout2)
        self.assertEqual(
            model.layoutFromIndex(model.index(1, 0, QModelIndex())), None)
        self.assertEqual(model.indexFromLayout(layout2),
                         model.index(0, 0, QModelIndex()))

        manager.clear()
        self.assertEqual(model.rowCount(QModelIndex()), 0)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)

        # with empty row
        model.setAllowEmptyLayout(True)
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)

        layout = QgsPrintLayout(project)
        layout.setName('test layout')
        self.assertTrue(manager.addLayout(layout))
        self.assertEqual(model.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'test layout')
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            model.data(model.index(2, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(2, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(1, 0, QModelIndex())), layout)
        self.assertEqual(model.indexFromLayout(layout),
                         model.index(1, 0, QModelIndex()))

        layout2 = QgsPrintLayout(project)
        layout2.setName('test layout2')
        self.assertTrue(manager.addLayout(layout2))
        self.assertEqual(model.rowCount(QModelIndex()), 3)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'test layout')
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout)
        self.assertEqual(
            model.data(model.index(2, 0, QModelIndex()), Qt.DisplayRole),
            'test layout2')
        self.assertEqual(
            model.data(model.index(2, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), layout2)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(1, 0, QModelIndex())), layout)
        self.assertEqual(
            model.layoutFromIndex(model.index(2, 0, QModelIndex())), layout2)
        self.assertEqual(model.indexFromLayout(layout),
                         model.index(1, 0, QModelIndex()))
        self.assertEqual(model.indexFromLayout(layout2),
                         model.index(2, 0, QModelIndex()))

        manager.clear()
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole), None)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsLayoutManagerModel.LayoutRole), None)
        self.assertEqual(
            model.layoutFromIndex(model.index(0, 0, QModelIndex())), None)