def test_getcapabilities(self):
        project = self._project_path
        assert os.path.exists(project), "Project file not found: " + project

        # without cache
        query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        doc = QDomDocument("wms_getcapabilities_130.xml")
        doc.setContent(body)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.1.1&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.1.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.0.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WCS&VERSION=1.0.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        # without cache
        query_string = '?MAP=%s&SERVICE=WMTS&VERSION=1.0.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        header, body = self._execute_request(query_string)
        # with cache
        header, body = self._execute_request(query_string)

        filelist = [
            f for f in os.listdir(self._servercache._cache_dir)
            if f.endswith(".xml")
        ]
        self.assertEqual(len(filelist), 6, 'Not enough file in cache')

        cacheManager = self._server_iface.cacheManager()

        self.assertTrue(cacheManager.deleteCachedDocuments(None),
                        'deleteCachedDocuments does not return True')

        filelist = [
            f for f in os.listdir(self._servercache._cache_dir)
            if f.endswith(".xml")
        ]
        self.assertEqual(len(filelist), 0,
                         'All files in cache are not deleted ')

        prj = QgsProject()
        prj.read(project)

        query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % (
            urllib.parse.quote(project), 'GetCapabilities')
        request = QgsBufferServerRequest(query_string,
                                         QgsServerRequest.GetMethod, {}, None)

        accessControls = self._server_iface.accessControls()

        cDoc = QDomDocument("wms_getcapabilities_130.xml")
        self.assertFalse(
            cacheManager.getCachedDocument(cDoc, prj, request, accessControls),
            'getCachedDocument is not None')

        self.assertTrue(
            cacheManager.setCachedDocument(doc, prj, request, accessControls),
            'setCachedDocument false')

        self.assertTrue(
            cacheManager.getCachedDocument(cDoc, prj, request, accessControls),
            'getCachedDocument is None')
        self.assertEqual(doc.documentElement().tagName(),
                         cDoc.documentElement().tagName(),
                         'cachedDocument not equal to provide document')

        self.assertTrue(cacheManager.deleteCachedDocuments(None),
                        'deleteCachedDocuments does not return True')
Example #2
0
    def testResizeToContents(self):
        p = QgsProject()
        l = QgsLayout(p)

        shape1 = QgsLayoutItemShape(l)
        shape1.attemptResize(QgsLayoutSize(90, 50))
        shape1.attemptMove(QgsLayoutPoint(90, 50))
        shape1.setItemRotation(45, False)
        l.addLayoutItem(shape1)
        shape2 = QgsLayoutItemShape(l)
        shape2.attemptResize(QgsLayoutSize(110, 50))
        shape2.attemptMove(QgsLayoutPoint(100, 150), True, False, 0)
        l.addLayoutItem(shape2)
        shape3 = QgsLayoutItemShape(l)
        l.addLayoutItem(shape3)
        shape3.attemptResize(QgsLayoutSize(50, 100))
        shape3.attemptMove(QgsLayoutPoint(210, 250), True, False, 0)
        shape4 = QgsLayoutItemShape(l)
        l.addLayoutItem(shape4)
        shape4.attemptResize(QgsLayoutSize(50, 30))
        shape4.attemptMove(QgsLayoutPoint(10, 340), True, False, 0)
        shape4.setVisibility(False)

        # resize with no existing pages
        l.pageCollection().resizeToContents(QgsMargins(1, 2, 3, 4),
                                            QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(l.pageCollection().pageCount(), 1)

        self.assertAlmostEqual(
            l.pageCollection().page(0).sizeWithUnits().width(), 290.3, 2)
        self.assertAlmostEqual(
            l.pageCollection().page(0).sizeWithUnits().height(), 380.36, 2)
        self.assertAlmostEqual(
            l.pageCollection().page(0).sizeWithUnits().units(),
            QgsUnitTypes.LayoutMillimeters)

        self.assertAlmostEqual(shape1.positionWithUnits().x(), 90.15, 2)
        self.assertAlmostEqual(shape1.positionWithUnits().y(), 20.21, 2)
        self.assertAlmostEqual(shape2.positionWithUnits().x(), 100.15, 2)
        self.assertAlmostEqual(shape2.positionWithUnits().y(), 120.21, 2)
        self.assertAlmostEqual(shape3.positionWithUnits().x(), 210.15, 2)
        self.assertAlmostEqual(shape3.positionWithUnits().y(), 220.21, 2)
        self.assertAlmostEqual(shape4.positionWithUnits().x(), 10.15, 2)
        self.assertAlmostEqual(shape4.positionWithUnits().y(), 310.21, 2)

        # add a second page
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize("A4", QgsLayoutItemPage.Landscape)
        l.pageCollection().addPage(page2)

        # add some guides
        g1 = QgsLayoutGuide(
            Qt.Horizontal,
            QgsLayoutMeasurement(2.5, QgsUnitTypes.LayoutCentimeters),
            l.pageCollection().page(0))
        l.guides().addGuide(g1)
        g2 = QgsLayoutGuide(
            Qt.Vertical,
            QgsLayoutMeasurement(4.5, QgsUnitTypes.LayoutCentimeters),
            l.pageCollection().page(0))
        l.guides().addGuide(g2)

        # second page should be removed
        l.pageCollection().resizeToContents(QgsMargins(0, 0, 0, 0),
                                            QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(l.pageCollection().pageCount(), 1)

        self.assertAlmostEqual(
            l.pageCollection().page(0).sizeWithUnits().width(), 250.3, 2)
        self.assertAlmostEqual(
            l.pageCollection().page(0).sizeWithUnits().height(), 320.36, 2)
        self.assertAlmostEqual(
            l.pageCollection().page(0).sizeWithUnits().units(),
            QgsUnitTypes.LayoutMillimeters)

        self.assertAlmostEqual(g1.position().length(), 0.5, 2)
        self.assertAlmostEqual(g2.position().length(), 3.5, 2)
Example #3
0
    def testPredictionPageNumberForPoint(self):
        """
        Test predictPageNumberForPoint
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        # no crash if no pages
        self.assertEqual(collection.predictPageNumberForPoint(QPointF(1, 1)),
                         0)

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize(QgsLayoutSize(100, 100))
        collection.addPage(page)

        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 20)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 120)), 1)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 230)), 2)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 350)), 3)

        page2 = QgsLayoutItemPage(l)
        page2.setPageSize(QgsLayoutSize(100, 50))
        collection.addPage(page2)

        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 20)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 120)), 1)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 230)), 2)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 280)), 3)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 340)), 4)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 370)), 5)

        page3 = QgsLayoutItemPage(l)
        page3.setPageSize(QgsLayoutSize(100, 200))
        collection.addPage(page3)

        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, -100)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, -1)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 20)), 0)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 120)), 1)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 230)), 2)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 280)), 2)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 340)), 2)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 370)), 2)
        self.assertEqual(
            collection.predictPageNumberForPoint(QPointF(-100, 470)), 3)
Example #4
0
    def testAlign(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemPicture(l)
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemPicture(l)
        item2.attemptMove(QgsLayoutPoint(6, 10, QgsUnitTypes.LayoutMillimeters))
        item2.attemptResize(QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item2)
        item3 = QgsLayoutItemPicture(l)
        item3.attemptMove(QgsLayoutPoint(0.8, 1.2, QgsUnitTypes.LayoutCentimeters))
        item3.attemptResize(QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item3)

        view = QgsLayoutView()
        view.setCurrentLayout(l)

        view.alignSelectedItems(QgsLayoutAligner.AlignLeft)

        item1.setSelected(True)
        item2.setSelected(True)
        item3.setSelected(True)

        view.alignSelectedItems(QgsLayoutAligner.AlignLeft)
        self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(4, 10, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item3.positionWithUnits(), QgsLayoutPoint(0.4, 1.2, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.alignSelectedItems(QgsLayoutAligner.AlignHCenter)
        self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(8, 10, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item3.positionWithUnits(), QgsLayoutPoint(0.4, 1.2, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.alignSelectedItems(QgsLayoutAligner.AlignRight)
        self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(12, 10, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item3.positionWithUnits(), QgsLayoutPoint(0.4, 1.2, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.alignSelectedItems(QgsLayoutAligner.AlignTop)
        self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(12, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item3.positionWithUnits(), QgsLayoutPoint(0.4, 0.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.alignSelectedItems(QgsLayoutAligner.AlignVCenter)
        self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 10, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(12, 11.5, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item3.positionWithUnits(), QgsLayoutPoint(0.4, 0.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.alignSelectedItems(QgsLayoutAligner.AlignBottom)
        self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(12, 15, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item3.positionWithUnits(), QgsLayoutPoint(0.4, 0.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
Example #5
0
    def testCopyPaste(self):
        p = QgsProject()
        l = QgsLayout(p)

        # clear clipboard
        mime_data = QMimeData()
        mime_data.setData("text/xml", QByteArray())
        clipboard = QApplication.clipboard()
        clipboard.setMimeData(mime_data)

        # add an item
        item1 = QgsLayoutItemLabel(l)
        item1.setText('label 1')
        l.addLayoutItem(item1)
        item1.setSelected(True)
        item2 = QgsLayoutItemLabel(l)
        item2.setText('label 2')
        l.addLayoutItem(item2)
        item2.setSelected(True)

        # multiframes
        multiframe1 = QgsLayoutItemHtml(l)
        multiframe1.setHtml('mf1')
        l.addMultiFrame(multiframe1)
        frame1 = QgsLayoutFrame(l, multiframe1)
        frame1.setId('frame1a')
        multiframe1.addFrame(frame1)
        frame1b = QgsLayoutFrame(l, multiframe1)
        frame1b.setId('frame1b')
        multiframe1.addFrame(frame1b) # not selected
        frame1c = QgsLayoutFrame(l, multiframe1)
        frame1c.setId('frame1b')
        multiframe1.addFrame(frame1c) # not selected

        multiframe2 = QgsLayoutItemHtml(l)
        multiframe2.setHtml('mf2')
        l.addMultiFrame(multiframe2)
        frame2 = QgsLayoutFrame(l, multiframe2)
        frame2.setId('frame2')
        multiframe2.addFrame(frame2)

        frame1.setSelected(True)
        frame2.setSelected(True)

        view = QgsLayoutView()
        view.setCurrentLayout(l)
        self.assertFalse(view.hasItemsInClipboard())

        view.copySelectedItems(QgsLayoutView.ClipboardCopy)
        self.assertTrue(view.hasItemsInClipboard())

        pasted = view.pasteItems(QgsLayoutView.PasteModeCursor)
        self.assertEqual(len(pasted), 4)

        new_multiframes = [m for m in l.multiFrames() if m not in [multiframe1, multiframe2]]
        self.assertEqual(len(new_multiframes), 2)

        self.assertIn(pasted[0], l.items())
        self.assertIn(pasted[1], l.items())
        labels = [p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutLabel]
        self.assertIn(sip.cast(labels[0], QgsLayoutItemLabel).text(), ('label 1', 'label 2'))
        self.assertIn(sip.cast(labels[1], QgsLayoutItemLabel).text(), ('label 1', 'label 2'))
        frames = [p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutFrame]
        pasted_frame1 = sip.cast(frames[0], QgsLayoutFrame)
        pasted_frame2 = sip.cast(frames[1], QgsLayoutFrame)
        self.assertIn(pasted_frame1.multiFrame(), new_multiframes)
        self.assertIn(new_multiframes[0].frames()[0].uuid(), (pasted_frame1.uuid(), pasted_frame2.uuid()))
        self.assertIn(pasted_frame2.multiFrame(), new_multiframes)
        self.assertIn(new_multiframes[1].frames()[0].uuid(), (pasted_frame1.uuid(), pasted_frame2.uuid()))

        self.assertEqual(frame1.multiFrame(), multiframe1)
        self.assertCountEqual(multiframe1.frames(), [frame1, frame1b, frame1c])
        self.assertEqual(frame1b.multiFrame(), multiframe1)
        self.assertEqual(frame1c.multiFrame(), multiframe1)
        self.assertEqual(frame2.multiFrame(), multiframe2)
        self.assertCountEqual(multiframe2.frames(), [frame2])

        # copy specific item
        view.copyItems([item2], QgsLayoutView.ClipboardCopy)
        l2 = QgsLayout(p)
        view2 = QgsLayoutView()
        view2.setCurrentLayout(l2)
        pasted = view2.pasteItems(QgsLayoutView.PasteModeCursor)
        self.assertEqual(len(pasted), 1)
        self.assertIn(pasted[0], l2.items())
        self.assertEqual(sip.cast(pasted[0], QgsLayoutItemLabel).text(), 'label 2')
Example #6
0
    def testHomePath(self):
        p = QgsProject()
        path_changed_spy = QSignalSpy(p.homePathChanged)
        self.assertFalse(p.homePath())
        self.assertFalse(p.presetHomePath())

        # simulate save file
        tmp_dir = QTemporaryDir()
        tmp_file = "{}/project.qgs".format(tmp_dir.path())
        with open(tmp_file, 'w') as f:
            pass
        p.setFileName(tmp_file)

        # home path should be file path
        self.assertEqual(p.homePath(), tmp_dir.path())
        self.assertFalse(p.presetHomePath())
        self.assertEqual(len(path_changed_spy), 1)

        # manually override home path
        p.setPresetHomePath('/tmp/my_path')
        self.assertEqual(p.homePath(), '/tmp/my_path')
        self.assertEqual(p.presetHomePath(), '/tmp/my_path')
        self.assertEqual(len(path_changed_spy), 2)
        # check project scope
        scope = QgsExpressionContextUtils.projectScope(p)
        self.assertEqual(scope.variable('project_home'), '/tmp/my_path')

        # no extra signal if path is unchanged
        p.setPresetHomePath('/tmp/my_path')
        self.assertEqual(p.homePath(), '/tmp/my_path')
        self.assertEqual(p.presetHomePath(), '/tmp/my_path')
        self.assertEqual(len(path_changed_spy), 2)

        # setting file name should not affect home path is manually set
        tmp_file_2 = "{}/project/project2.qgs".format(tmp_dir.path())
        os.mkdir(tmp_dir.path() + '/project')
        with open(tmp_file_2, 'w') as f:
            pass
        p.setFileName(tmp_file_2)
        self.assertEqual(p.homePath(), '/tmp/my_path')
        self.assertEqual(p.presetHomePath(), '/tmp/my_path')
        self.assertEqual(len(path_changed_spy), 2)

        scope = QgsExpressionContextUtils.projectScope(p)
        self.assertEqual(scope.variable('project_home'), '/tmp/my_path')

        # clear manual path
        p.setPresetHomePath('')
        self.assertEqual(p.homePath(), tmp_dir.path() + '/project')
        self.assertFalse(p.presetHomePath())
        self.assertEqual(len(path_changed_spy), 3)

        scope = QgsExpressionContextUtils.projectScope(p)
        self.assertEqual(scope.variable('project_home'), tmp_dir.path() + '/project')

        # relative path
        p.setPresetHomePath('../home')
        self.assertEqual(p.homePath(), tmp_dir.path() + '/home')
        self.assertEqual(p.presetHomePath(), '../home')
        self.assertEqual(len(path_changed_spy), 4)

        scope = QgsExpressionContextUtils.projectScope(p)
        self.assertEqual(scope.variable('project_home'), tmp_dir.path() + '/home')

        # relative path, no filename
        p.setFileName('')
        self.assertEqual(p.homePath(), '../home')
        self.assertEqual(p.presetHomePath(), '../home')

        scope = QgsExpressionContextUtils.projectScope(p)
        self.assertEqual(scope.variable('project_home'), '../home')
Example #7
0
    def testSelectNextByZOrder(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemPicture(l)
        l.addItem(item1)
        item2 = QgsLayoutItemPicture(l)
        l.addItem(item2)
        item3 = QgsLayoutItemPicture(l)
        item3.setLocked(True)
        l.addItem(item3)

        view = QgsLayoutView()
        # no layout, no crash
        view.selectNextItemAbove()
        view.selectNextItemBelow()

        view.setCurrentLayout(l)

        focused_item_spy = QSignalSpy(view.itemFocused)

        # no selection
        view.selectNextItemAbove()
        view.selectNextItemBelow()
        self.assertEqual(len(focused_item_spy), 0)

        l.setSelectedItem(item1)
        self.assertEqual(len(focused_item_spy), 1)
        # already bottom most
        view.selectNextItemBelow()
        self.assertTrue(item1.isSelected())
        self.assertFalse(item2.isSelected())
        self.assertFalse(item3.isSelected())
        self.assertEqual(len(focused_item_spy), 1)

        view.selectNextItemAbove()
        self.assertFalse(item1.isSelected())
        self.assertTrue(item2.isSelected())
        self.assertFalse(item3.isSelected())
        self.assertEqual(len(focused_item_spy), 2)

        view.selectNextItemAbove()
        self.assertFalse(item1.isSelected())
        self.assertFalse(item2.isSelected())
        self.assertTrue(item3.isSelected())
        self.assertEqual(len(focused_item_spy), 3)

        view.selectNextItemAbove() # already top most
        self.assertFalse(item1.isSelected())
        self.assertFalse(item2.isSelected())
        self.assertTrue(item3.isSelected())
        self.assertEqual(len(focused_item_spy), 3)

        view.selectNextItemBelow()
        self.assertFalse(item1.isSelected())
        self.assertTrue(item2.isSelected())
        self.assertFalse(item3.isSelected())
        self.assertEqual(len(focused_item_spy), 4)

        view.selectNextItemBelow()
        self.assertTrue(item1.isSelected())
        self.assertFalse(item2.isSelected())
        self.assertFalse(item3.isSelected())
        self.assertEqual(len(focused_item_spy), 5)

        view.selectNextItemBelow() # back to bottom most
        self.assertTrue(item1.isSelected())
        self.assertFalse(item2.isSelected())
        self.assertFalse(item3.isSelected())
        self.assertEqual(len(focused_item_spy), 5)
Example #8
0
    def testProjectStorage(self):
        # New project without fileName
        p0 = QgsProject()
        self.assertTrue(p0.auxiliaryStorage().isValid())

        # Create new layers with key otherwise auxiliary layers are not
        # automacially created when added in project
        vl0 = createLayer()
        vl0Shp = writeShape(vl0, 'vl0.shp')

        vl1 = createLayer()
        vl1Shp = writeShape(vl1, 'vl1.shp')

        vl0 = QgsVectorLayer(vl0Shp, 'points', 'ogr')
        self.assertTrue(vl0.isValid())

        vl1 = QgsVectorLayer(vl1Shp, 'points', 'ogr')
        self.assertTrue(vl1.isValid())

        # Add layers to project and check underlying auxiliary layers
        p0.addMapLayers([vl0, vl1])

        self.assertTrue(vl0.loadAuxiliaryLayer(p0.auxiliaryStorage(), 'pk'))
        self.assertTrue(
            vl1.loadAuxiliaryLayer(p0.auxiliaryStorage(), 'num_char'))

        al0 = vl0.auxiliaryLayer()
        al1 = vl1.auxiliaryLayer()

        self.assertEqual(al0.joinInfo().targetFieldName(), 'pk')
        self.assertEqual(al1.joinInfo().targetFieldName(), 'num_char')

        # Add a field in auxiliary layers
        pdef0 = QgsPropertyDefinition('propname',
                                      QgsPropertyDefinition.DataTypeNumeric,
                                      '', '', 'ut')
        self.assertTrue(al0.addAuxiliaryField(pdef0))

        pdef1 = QgsPropertyDefinition('propname1',
                                      QgsPropertyDefinition.DataTypeString, '',
                                      '', 'ut')
        self.assertTrue(al1.addAuxiliaryField(pdef1))

        # Check auxiliary fields names
        af0Name = QgsAuxiliaryLayer.nameFromProperty(pdef0, False)
        self.assertEqual(af0Name, 'ut_propname')
        af1Name = QgsAuxiliaryLayer.nameFromProperty(pdef1, False)
        self.assertEqual(af1Name, 'ut_propname1')

        # Set value for auxiliary fields
        req = QgsFeatureRequest().setFilterExpression("name = 'Honey'")
        f = QgsFeature()
        vl0.getFeatures(req).nextFeature(f)
        self.assertTrue(f.isValid())
        af0Name = QgsAuxiliaryLayer.nameFromProperty(pdef0, True)
        index0 = vl0.fields().indexOf(af0Name)
        vl0.changeAttributeValue(f.id(), index0, 333)

        req = QgsFeatureRequest().setFilterExpression("name = 'Apple'")
        f = QgsFeature()
        vl1.getFeatures(req).nextFeature(f)
        self.assertTrue(f.isValid())
        af1Name = QgsAuxiliaryLayer.nameFromProperty(pdef1, True)
        index1 = vl1.fields().indexOf(af1Name)
        vl1.changeAttributeValue(f.id(), index0, 'myvalue')

        req = QgsFeatureRequest().setFilterExpression("name = 'Orange'")
        f = QgsFeature()
        vl1.getFeatures(req).nextFeature(f)
        self.assertTrue(f.isValid())
        vl1.changeAttributeValue(f.id(), index0, 'myvalue1')

        # Save the project in a zip file
        f = tmpPath() + '.qgz'
        p0.write(f)

        # Open the zip file with embedded auxiliary storage
        p1 = QgsProject()
        p1.read(f)

        # Check that auxiliary fields are well loaded in layers
        self.assertEqual(len(p1.mapLayers().values()), 2)

        for vl in p1.mapLayers().values():
            al = vl.auxiliaryLayer()
            self.assertEqual(len(al.auxiliaryFields()), 1)

            af = al.auxiliaryFields()[0]
            afPropDef = QgsAuxiliaryLayer.propertyDefinitionFromField(af)
            self.assertEqual(afPropDef.origin(), 'ut')

            if vl.auxiliaryLayer().joinInfo().targetFieldName() == 'pk':
                self.assertEqual(afPropDef.name(), 'propname')
                self.assertEqual(al.featureCount(), 1)

                req = QgsFeatureRequest().setFilterExpression("name = 'Honey'")
                f = QgsFeature()
                vl.getFeatures(req).nextFeature(f)
                self.assertTrue(f.isValid())
                self.assertEqual(f.attributes()[index0], 333.0)
            else:  # num_char
                self.assertEqual(al.featureCount(), 2)
                self.assertEqual(afPropDef.name(), 'propname1')

                req = QgsFeatureRequest().setFilterExpression("name = 'Apple'")
                f = QgsFeature()
                vl.getFeatures(req).nextFeature(f)
                self.assertTrue(f.isValid())
                self.assertEqual(f.attributes()[index1], 'myvalue')

                req = QgsFeatureRequest().setFilterExpression(
                    "name = 'Orange'")
                f = QgsFeature()
                vl.getFeatures(req).nextFeature(f)
                self.assertTrue(f.isValid())
                self.assertEqual(f.attributes()[index1], 'myvalue1')
Example #9
0
    def testRelativePaths(self):
        """
        Test whether paths to layer sources are stored as relative to the project path
        """
        tmpDir = QTemporaryDir()
        tmpFile = "{}/project.qgs".format(tmpDir.path())
        copyfile(os.path.join(TEST_DATA_DIR, "points.shp"),
                 os.path.join(tmpDir.path(), "points.shp"))
        copyfile(os.path.join(TEST_DATA_DIR, "points.dbf"),
                 os.path.join(tmpDir.path(), "points.dbf"))
        copyfile(os.path.join(TEST_DATA_DIR, "points.shx"),
                 os.path.join(tmpDir.path(), "points.shx"))
        copyfile(os.path.join(TEST_DATA_DIR, "lines.shp"),
                 os.path.join(tmpDir.path(), "lines.shp"))
        copyfile(os.path.join(TEST_DATA_DIR, "lines.dbf"),
                 os.path.join(tmpDir.path(), "lines.dbf"))
        copyfile(os.path.join(TEST_DATA_DIR, "lines.shx"),
                 os.path.join(tmpDir.path(), "lines.shx"))
        copyfile(os.path.join(TEST_DATA_DIR, "landsat_4326.tif"),
                 os.path.join(tmpDir.path(), "landsat_4326.tif"))

        project = QgsProject()

        l0 = QgsVectorLayer(os.path.join(tmpDir.path(), "points.shp"),
                            "points", "ogr")
        l1 = QgsVectorLayer(os.path.join(tmpDir.path(), "lines.shp"), "lines",
                            "ogr")
        l2 = QgsRasterLayer(os.path.join(tmpDir.path(), "landsat_4326.tif"),
                            "landsat", "gdal")
        self.assertTrue(l0.isValid())
        self.assertTrue(l1.isValid())
        self.assertTrue(l2.isValid())
        self.assertTrue(project.addMapLayers([l0, l1, l2]))
        self.assertTrue(project.write(tmpFile))
        del project

        with open(tmpFile, 'r') as f:
            content = ''.join(f.readlines())
            self.assertTrue('source="./lines.shp"' in content)
            self.assertTrue('source="./points.shp"' in content)
            self.assertTrue('source="./landsat_4326.tif"' in content)

        # Re-read the project and store absolute
        project = QgsProject()
        self.assertTrue(project.read(tmpFile))
        store = project.layerStore()
        self.assertEquals(set([l.name() for l in store.mapLayers().values()]),
                          set(['lines', 'landsat', 'points']))
        project.writeEntryBool('Paths', '/Absolute', True)
        tmpFile2 = "{}/project2.qgs".format(tmpDir.path())
        self.assertTrue(project.write(tmpFile2))

        with open(tmpFile2, 'r') as f:
            content = ''.join(f.readlines())
            self.assertTrue(
                'source="{}/lines.shp"'.format(tmpDir.path()) in content)
            self.assertTrue(
                'source="{}/points.shp"'.format(tmpDir.path()) in content)
            self.assertTrue('source="{}/landsat_4326.tif"'.format(
                tmpDir.path()) in content)

        del project
Example #10
0
    def testFieldGroupMultiLayer(self):
        # create a layer
        states = QgsVectorLayer("Point?crs=epsg:4326&field=country:string(20)&field=state:string(20)", "points", "memory")

        attributes = [
            ['Australia', 'QLD'],
            ['NZ', 'state1'],
            ['Australia', 'VIC'],
            ['NZ', 'state2'],
            ['PNG', 'state3'],
            ['Australia', 'NSW']
        ]

        pr = states.dataProvider()
        for a in attributes:
            f = QgsFeature()
            f.initAttributes(2)
            f.setAttribute(0, a[0])
            f.setAttribute(1, a[1])
            self.assertTrue(pr.addFeature(f))

        places = QgsVectorLayer("Point?crs=epsg:4326&field=state:string(20)&field=town:string(20)", "points", "memory")

        attributes = [
            ['QLD', 'Brisbane'],
            ['QLD', 'Emerald'],
            ['state1', 'town1'],
            ['VIC', 'Melbourne'],
            ['state1', 'town2'],
            ['QLD', 'Beerburrum'],
            ['VIC', 'Geelong'],
            ['state3', 'town1']
        ]

        pr = places.dataProvider()
        for a in attributes:
            f = QgsFeature()
            f.initAttributes(2)
            f.setAttribute(0, a[0])
            f.setAttribute(1, a[1])
            self.assertTrue(pr.addFeature(f))

        p = QgsProject()
        r = QgsReport(p)

        # add a child
        child1 = QgsReportSectionFieldGroup()
        child1_body = QgsLayout(p)
        child1.setLayer(states)
        child1.setBody(child1_body)
        child1.setBodyEnabled(True)
        child1.setField('country')
        r.appendChild(child1)
        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'QLD'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'VIC'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'NSW'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state2'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['PNG', 'state3'])
        self.assertFalse(r.next())

        # another group
        # remove body from child1
        child1.setBodyEnabled(False)

        child2 = QgsReportSectionFieldGroup()
        child2_body = QgsLayout(p)
        child2.setLayer(states)
        child2.setBody(child2_body)
        child2.setBodyEnabled(True)
        child2.setField('state')
        child1.appendChild(child2)
        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'NSW'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'QLD'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'VIC'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state2'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['PNG', 'state3'])
        self.assertFalse(r.next())

        # another group

        child3 = QgsReportSectionFieldGroup()
        child3_body = QgsLayout(p)
        child3.setLayer(places)
        child3.setBody(child3_body)
        child3.setBodyEnabled(True)
        child3.setField('town')
        child3.setSortAscending(False)
        child2.appendChild(child3)
        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'NSW'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'QLD'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Emerald'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Brisbane'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Beerburrum'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'VIC'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['VIC', 'Melbourne'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['VIC', 'Geelong'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state1', 'town2'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state1', 'town1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state2'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['PNG', 'state3'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state3', 'town1'])
        self.assertFalse(r.next())

        # add headers/footers
        child3_header = QgsLayout(p)
        child3.setHeader(child3_header)
        child3.setHeaderEnabled(True)
        child3_footer = QgsLayout(p)
        child3.setFooter(child3_footer)
        child3.setFooterEnabled(True)

        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'NSW'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'QLD'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_header)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Emerald'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Emerald'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Brisbane'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Beerburrum'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_footer)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['QLD', 'Beerburrum'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['Australia', 'VIC'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_header)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['VIC', 'Melbourne'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['VIC', 'Melbourne'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['VIC', 'Geelong'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_footer)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['VIC', 'Geelong'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_header)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state1', 'town2'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state1', 'town2'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state1', 'town1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_footer)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state1', 'town1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['NZ', 'state2'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['PNG', 'state3'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_header)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state3', 'town1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_body)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state3', 'town1'])
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child3_footer)
        self.assertEqual(r.layout().reportContext().feature().attributes(), ['state3', 'town1'])
        self.assertFalse(r.next())
Example #11
0
    def test_read_write_project2(self):
        """
        Test reading and writing to project, signals based
        """
        p = QgsProject()
        original = PlotSettings('test',
                                properties={
                                    'marker_width': 2,
                                    'marker_size': 5
                                },
                                layout={
                                    'title': 'my plot',
                                    'legend_orientation': 'v',
                                    'font_xlabel_color': '#00FFFF'
                                })
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_FILTER,
            QgsProperty.fromExpression('"ap">50'))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_MARKER_SIZE,
            QgsProperty.fromExpression('5+6'))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_COLOR, QgsProperty.fromExpression("'red'"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_STROKE_WIDTH,
            QgsProperty.fromExpression('12/2'))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_TITLE,
            QgsProperty.fromExpression("concat('my', '_title')"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_LEGEND_TITLE,
            QgsProperty.fromExpression("concat('my', '_legend')"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_X_TITLE,
            QgsProperty.fromExpression("concat('my', '_x_axis')"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_Y_TITLE,
            QgsProperty.fromExpression("concat('my', '_y_axis')"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_Z_TITLE,
            QgsProperty.fromExpression("concat('my', '_z_axis')"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_X_MIN, QgsProperty.fromExpression("-1*10"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_X_MAX, QgsProperty.fromExpression("+1*10"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_Y_MIN, QgsProperty.fromExpression("-1*10"))
        original.data_defined_properties.setProperty(
            PlotSettings.PROPERTY_Y_MAX, QgsProperty.fromExpression("+1*10"))

        self.test_read_write_project2_written = False

        def write(doc):
            self.test_read_write_project2_written = True
            original.write_to_project(doc)

        p.writeProject.connect(write)

        path = os.path.join(tempfile.gettempdir(),
                            'test_dataplotly_project.qgs')
        self.assertTrue(p.write(path))
        for _ in range(100):
            QCoreApplication.processEvents()
        self.assertTrue(self.test_read_write_project2_written)

        p2 = QgsProject()
        res = PlotSettings('gg')
        self.test_read_write_project2_read = False

        def read(doc):
            res.read_from_project(doc)
            self.test_read_write_project2_read = True

        p2.readProject.connect(read)
        self.assertTrue(p2.read(path))
        for _ in range(100):
            QCoreApplication.processEvents()
        self.assertTrue(self.test_read_write_project2_read)

        self.assertEqual(res.plot_type, original.plot_type)
        self.assertEqual(res.properties, original.properties)
        self.assertEqual(res.layout, original.layout)
        self.assertEqual(
            res.data_defined_properties.property(PlotSettings.PROPERTY_FILTER),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_FILTER))
        self.assertEqual(
            res.data_defined_properties.property(
                PlotSettings.PROPERTY_MARKER_SIZE),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_MARKER_SIZE))
        self.assertEqual(
            res.data_defined_properties.property(PlotSettings.PROPERTY_COLOR),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_COLOR))
        self.assertEqual(
            res.data_defined_properties.property(
                PlotSettings.PROPERTY_STROKE_WIDTH),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_STROKE_WIDTH))
        self.assertEqual(
            res.data_defined_properties.property(PlotSettings.PROPERTY_TITLE),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_TITLE))
        self.assertEqual(
            res.data_defined_properties.property(
                PlotSettings.PROPERTY_LEGEND_TITLE),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_LEGEND_TITLE))
        self.assertEqual(
            res.data_defined_properties.property(
                PlotSettings.PROPERTY_X_TITLE),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_X_TITLE))
        self.assertEqual(
            res.data_defined_properties.property(
                PlotSettings.PROPERTY_Y_TITLE),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_Y_TITLE))
        self.assertEqual(
            res.data_defined_properties.property(
                PlotSettings.PROPERTY_Z_TITLE),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_Z_TITLE))
        self.assertEqual(
            res.data_defined_properties.property(PlotSettings.PROPERTY_X_MIN),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_X_MIN))
        self.assertEqual(
            res.data_defined_properties.property(PlotSettings.PROPERTY_X_MAX),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_X_MAX))
        self.assertEqual(
            res.data_defined_properties.property(PlotSettings.PROPERTY_Y_MIN),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_Y_MIN))
        self.assertEqual(
            res.data_defined_properties.property(PlotSettings.PROPERTY_Y_MAX),
            original.data_defined_properties.property(
                PlotSettings.PROPERTY_Y_MAX))
Example #12
0
    def testIteration(self):
        p = QgsProject()
        r = QgsReport(p)

        # empty report
        self.assertTrue(r.beginRender())
        self.assertFalse(r.next())

        # add a header
        r.setHeaderEnabled(True)
        report_header = QgsLayout(p)
        r.setHeader(report_header)

        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_header)
        self.assertFalse(r.next())

        # add a footer
        r.setFooterEnabled(True)
        report_footer = QgsLayout(p)
        r.setFooter(report_footer)

        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_header)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_footer)
        self.assertFalse(r.next())

        # add a child
        child1 = QgsReportSectionLayout()
        child1_body = QgsLayout(p)
        child1.setBody(child1_body)
        r.appendChild(child1)
        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_header)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_footer)
        self.assertFalse(r.next())

        # header and footer on child
        child1_header = QgsLayout(p)
        child1.setHeader(child1_header)
        child1.setHeaderEnabled(True)
        child1_footer = QgsLayout(p)
        child1.setFooter(child1_footer)
        child1.setFooterEnabled(True)
        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_header)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_header)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_footer)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_footer)
        self.assertFalse(r.next())

        # add another child
        child2 = QgsReportSectionLayout()
        child2_header = QgsLayout(p)
        child2.setHeader(child2_header)
        child2.setHeaderEnabled(True)
        child2_footer = QgsLayout(p)
        child2.setFooter(child2_footer)
        child2.setFooterEnabled(True)
        r.appendChild(child2)
        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_header)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_header)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_footer)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_header)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_footer)
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_footer)
        self.assertFalse(r.next())

        # add a child to child2
        child2a = QgsReportSectionLayout()
        child2a_header = QgsLayout(p)
        child2a.setHeader(child2a_header)
        child2a.setHeaderEnabled(True)
        child2a_footer = QgsLayout(p)
        child2a.setFooter(child2a_footer)
        child2a.setFooterEnabled(True)
        child2.appendChild(child2a)
        self.assertTrue(r.beginRender())
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_header)
        self.assertEqual(r.filePath('/tmp/myreport', 'png'), '/tmp/myreport_0001.png')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_header)
        self.assertEqual(r.filePath('/tmp/myreport', 'png'), '/tmp/myreport_0002.png')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_body)
        self.assertEqual(r.filePath('/tmp/myreport', '.png'), '/tmp/myreport_0003.png')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child1_footer)
        self.assertEqual(r.filePath('/tmp/myreport', 'jpg'), '/tmp/myreport_0004.jpg')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_header)
        self.assertEqual(r.filePath('/tmp/myreport', 'png'), '/tmp/myreport_0005.png')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2a_header)
        self.assertEqual(r.filePath('/tmp/myreport', 'png'), '/tmp/myreport_0006.png')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2a_footer)
        self.assertEqual(r.filePath('/tmp/myreport', 'png'), '/tmp/myreport_0007.png')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), child2_footer)
        self.assertEqual(r.filePath('/tmp/myreport', 'png'), '/tmp/myreport_0008.png')
        self.assertTrue(r.next())
        self.assertEqual(r.layout(), report_footer)
        self.assertEqual(r.filePath('/tmp/myreport', 'png'), '/tmp/myreport_0009.png')
        self.assertFalse(r.next())
Example #13
0
 def testReportSectionLayout(self):
     r = QgsReportSectionLayout()
     p = QgsProject()
     body = QgsLayout(p)
     r.setBody(body)
     self.assertEqual(r.body(), body)
Example #14
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')
Example #15
0
 def test_zip_invalid_path(self):
     project = QgsProject()
     self.assertFalse(project.write())
     self.assertFalse(project.write(""))
     self.assertFalse(project.write("/fake/test.zip"))
Example #16
0
    def testDuplicateFeature(self):
        """ test duplicating a feature """

        project = QgsProject().instance()

        # LAYERS
        # - add first layer (parent)
        layer1 = QgsVectorLayer("Point?field=fldtxt:string&field=pkid:integer",
                                "parentlayer", "memory")
        # > check first layer (parent)
        self.assertTrue(layer1.isValid())
        # -  set the value for the copy
        layer1.setDefaultValueDefinition(1, QgsDefaultValue("rand(1000,2000)"))
        # > check first layer (parent)
        self.assertTrue(layer1.isValid())
        # - add second layer (child)
        layer2 = QgsVectorLayer(
            "Point?field=fldtxt:string&field=id:integer&field=foreign_key:integer",
            "childlayer", "memory")
        # > check second layer (child)
        self.assertTrue(layer2.isValid())
        # - add layers
        project.addMapLayers([layer1, layer2])

        # FEATURES
        # - add 2 features on layer1 (parent)
        l1f1orig = QgsFeature()
        l1f1orig.setFields(layer1.fields())
        l1f1orig.setAttributes(["F_l1f1", 100])
        l1f2orig = QgsFeature()
        l1f2orig.setFields(layer1.fields())
        l1f2orig.setAttributes(["F_l1f2", 101])
        # > check by adding features
        self.assertTrue(layer1.dataProvider().addFeatures([l1f1orig,
                                                           l1f2orig]))
        # add 4 features on layer2 (child)
        l2f1orig = QgsFeature()
        l2f1orig.setFields(layer2.fields())
        l2f1orig.setAttributes(["F_l2f1", 201, 100])
        l2f2orig = QgsFeature()
        l2f2orig.setFields(layer2.fields())
        l2f2orig.setAttributes(["F_l2f2", 202, 100])
        l2f3orig = QgsFeature()
        l2f3orig.setFields(layer2.fields())
        l2f3orig.setAttributes(["F_l2f3", 203, 100])
        l2f4orig = QgsFeature()
        l2f4orig.setFields(layer2.fields())
        l2f4orig.setAttributes(["F_l2f4", 204, 101])
        # > check by adding features
        self.assertTrue(layer2.dataProvider().addFeatures(
            [l2f1orig, l2f2orig, l2f3orig, l2f4orig]))

        # RELATION
        # - create the relationmanager
        relMgr = project.relationManager()
        # - create the relation
        rel = QgsRelation()
        rel.setId('rel1')
        rel.setName('childrel')
        rel.setReferencingLayer(layer2.id())
        rel.setReferencedLayer(layer1.id())
        rel.addFieldPair('foreign_key', 'pkid')
        rel.setStrength(QgsRelation.Composition)
        # > check relation
        self.assertTrue(rel.isValid())
        # - add relation
        relMgr.addRelation(rel)
        # > check if referencedLayer is layer1
        self.assertEqual(rel.referencedLayer(), layer1)
        # > check if referencingLayer is layer2
        self.assertEqual(rel.referencingLayer(), layer2)
        # > check if the layers are correct in relation when loading from relationManager
        relations = project.relationManager().relations()
        relation = relations[list(relations.keys())[0]]
        # > check if referencedLayer is layer1
        self.assertEqual(relation.referencedLayer(), layer1)
        # > check if referencingLayer is layer2
        self.assertEqual(relation.referencingLayer(), layer2)
        # > check the relatedfeatures
        '''
        # testoutput 1
        print( "\nAll Features and relations")
        featit=layer1.getFeatures()
        f=QgsFeature()
        while featit.nextFeature(f):
            print( f.attributes())
            childFeature = QgsFeature()
            relfeatit=rel.getRelatedFeatures(f)
            while relfeatit.nextFeature(childFeature):
                 print( childFeature.attributes() )
        print( "\n--------------------------")

        print( "\nFeatures on layer1")
        for f in layer1.getFeatures():
            print( f.attributes() )

        print( "\nFeatures on layer2")
        for f in layer2.getFeatures():
            print( f.attributes() )
        '''

        # DUPLICATION
        # - duplicate feature l1f1orig with children
        layer1.startEditing()
        results = QgsVectorLayerUtils.duplicateFeature(layer1, l1f1orig,
                                                       project, 0)

        # > check if name is name of duplicated (pk is different)
        result_feature = results[0]
        self.assertEqual(result_feature.attribute('fldtxt'),
                         l1f1orig.attribute('fldtxt'))
        # > check duplicated child layer
        result_layer = results[1].layers()[0]
        self.assertEqual(result_layer, layer2)
        #  > check duplicated child features
        self.assertTrue(results[1].duplicatedFeatures(result_layer))
        '''
        # testoutput 2
        print( "\nFeatures on layer1 (after duplication)")
        for f in layer1.getFeatures():
            print( f.attributes() )

        print( "\nFeatures on layer2 (after duplication)")
        for f in layer2.getFeatures():
            print( f.attributes() )
            
        print( "\nAll Features and relations")
        featit=layer1.getFeatures()
        f=QgsFeature()
        while featit.nextFeature(f):
            print( f.attributes())
            childFeature = QgsFeature()
            relfeatit=rel.getRelatedFeatures(f)
            while relfeatit.nextFeature(childFeature):
                 print( childFeature.attributes() )
        '''

        # > compare text of parent feature
        self.assertEqual(result_feature.attribute('fldtxt'),
                         l1f1orig.attribute('fldtxt'))

        # - create copyValueList
        childFeature = QgsFeature()
        relfeatit = rel.getRelatedFeatures(result_feature)
        copyValueList = []
        while relfeatit.nextFeature(childFeature):
            copyValueList.append(childFeature.attribute('fldtxt'))
        # - create origValueList
        childFeature = QgsFeature()
        relfeatit = rel.getRelatedFeatures(l1f1orig)
        origValueList = []
        while relfeatit.nextFeature(childFeature):
            origValueList.append(childFeature.attribute('fldtxt'))

        # - check if the ids are still the same
        self.assertEqual(copyValueList, origValueList)
Example #17
0
 def test_unzip_invalid_path(self):
     project = QgsProject()
     self.assertFalse(project.read())
     self.assertFalse(project.read(""))
     self.assertFalse(project.read("/fake/test.zip"))
    def testPagePositionToAbsolute(self):
        """
        Test pagePositionToAbsolute
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        # invalid pages
        self.assertEqual(
            collection.pagePositionToAbsolute(-1, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        self.assertEqual(
            collection.pagePositionToAbsolute(0, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        self.assertEqual(
            collection.pagePositionToAbsolute(100, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))

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

        #invalid pages
        self.assertEqual(
            collection.pagePositionToAbsolute(-1, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        self.assertEqual(
            collection.pagePositionToAbsolute(1, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        #valid page
        self.assertEqual(
            collection.pagePositionToAbsolute(0, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        self.assertEqual(
            collection.pagePositionToAbsolute(0, QgsLayoutPoint(5, 6)),
            QgsLayoutPoint(5, 6))
        self.assertEqual(
            collection.pagePositionToAbsolute(
                0, QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)),
            QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters))

        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        #invalid pages
        self.assertEqual(
            collection.pagePositionToAbsolute(-1, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        self.assertEqual(
            collection.pagePositionToAbsolute(3, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        #valid pages
        self.assertEqual(
            collection.pagePositionToAbsolute(0, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 1))
        self.assertEqual(
            collection.pagePositionToAbsolute(0, QgsLayoutPoint(5, 6)),
            QgsLayoutPoint(5, 6))
        self.assertEqual(
            collection.pagePositionToAbsolute(
                0, QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)),
            QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(
            collection.pagePositionToAbsolute(1, QgsLayoutPoint(1, 1)),
            QgsLayoutPoint(1, 308.0))
        self.assertEqual(
            collection.pagePositionToAbsolute(1, QgsLayoutPoint(5, 6)),
            QgsLayoutPoint(5, 313.0))
        self.assertEqual(
            collection.pagePositionToAbsolute(
                1, QgsLayoutPoint(0.5, 0.6, QgsUnitTypes.LayoutCentimeters)),
            QgsLayoutPoint(0.5, 31.3, QgsUnitTypes.LayoutCentimeters))
Example #19
0
    def testDirtyBlocker(self):
        # first test manual QgsProjectDirtyBlocker construction
        p = QgsProject()

        dirty_spy = QSignalSpy(p.isDirtyChanged)
        # ^ will do *whatever* it takes to discover the enemy's secret plans!

        # simple checks
        p.setDirty(True)
        self.assertTrue(p.isDirty())
        self.assertEqual(len(dirty_spy), 1)
        self.assertEqual(dirty_spy[-1], [True])
        p.setDirty(True) # already dirty
        self.assertTrue(p.isDirty())
        self.assertEqual(len(dirty_spy), 1)
        p.setDirty(False)
        self.assertFalse(p.isDirty())
        self.assertEqual(len(dirty_spy), 2)
        self.assertEqual(dirty_spy[-1], [False])
        p.setDirty(True)
        self.assertTrue(p.isDirty())
        self.assertEqual(len(dirty_spy), 3)
        self.assertEqual(dirty_spy[-1], [True])

        # with a blocker
        blocker = QgsProjectDirtyBlocker(p)
        # blockers will allow cleaning projects
        p.setDirty(False)
        self.assertFalse(p.isDirty())
        self.assertEqual(len(dirty_spy), 4)
        self.assertEqual(dirty_spy[-1], [False])
        # but not dirtying!
        p.setDirty(True)
        self.assertFalse(p.isDirty())
        self.assertEqual(len(dirty_spy), 4)
        self.assertEqual(dirty_spy[-1], [False])
        # nested block
        blocker2 = QgsProjectDirtyBlocker(p)
        p.setDirty(True)
        self.assertFalse(p.isDirty())
        self.assertEqual(len(dirty_spy), 4)
        self.assertEqual(dirty_spy[-1], [False])
        del blocker2
        p.setDirty(True)
        self.assertFalse(p.isDirty())
        self.assertEqual(len(dirty_spy), 4)
        self.assertEqual(dirty_spy[-1], [False])
        del blocker
        p.setDirty(True)
        self.assertTrue(p.isDirty())
        self.assertEqual(len(dirty_spy), 5)
        self.assertEqual(dirty_spy[-1], [True])

        # using python context manager
        with QgsProject.blockDirtying(p):
            # cleaning allowed
            p.setDirty(False)
            self.assertFalse(p.isDirty())
            self.assertEqual(len(dirty_spy), 6)
            self.assertEqual(dirty_spy[-1], [False])
            # but not dirtying!
            p.setDirty(True)
            self.assertFalse(p.isDirty())
            self.assertEqual(len(dirty_spy), 6)
            self.assertEqual(dirty_spy[-1], [False])

        # unblocked
        p.setDirty(True)
        self.assertTrue(p.isDirty())
        self.assertEqual(len(dirty_spy), 7)
        self.assertEqual(dirty_spy[-1], [True])
Example #20
0
    def testAddItemsFromXml(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        doc = QDomDocument("testdoc")
        # store in xml
        elem = l.writeXml(doc, QgsReadWriteContext())

        l2 = QgsLayout(p)
        new_items = l2.addItemsFromXml(elem, doc, QgsReadWriteContext())
        self.assertEqual(len(new_items), 2)
        items = l2.items()
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        new_item1 = [i for i in items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item2.positionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))

        # test with a group
        group = QgsLayoutItemGroup(l)
        group.addItem(item1)
        group.addItem(item2)
        l.addLayoutItem(group)
        elem = l.writeXml(doc, QgsReadWriteContext())

        l3 = QgsLayout(p)
        new_items = l3.addItemsFromXml(elem, doc, QgsReadWriteContext())
        self.assertEqual(len(new_items), 3)
        items = l3.items()
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l3.items())
        self.assertTrue(new_items[1] in l3.items())
        self.assertTrue(new_items[2] in l3.items())

        # f*** you sip, I'll just manually cast
        new_group = sip.cast(l3.itemByUuid(group.uuid()), QgsLayoutItemGroup)
        self.assertIsNotNone(new_group)
        other_items = [i for i in new_items if i.type() != new_group.type()]
        self.assertCountEqual(new_group.items(), other_items)

        # test restoring at set position
        l3 = QgsLayout(p)
        new_items = l3.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 30))
        self.assertEqual(len(new_items), 3)
        items = l3.items()
        new_item1 = [i for i in items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.positionWithUnits(), QgsLayoutPoint(10, 30, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item2.positionWithUnits(), QgsLayoutPoint(2.0, 4.0, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))

        # paste in place
        l4 = QgsLayout(p)
        page = QgsLayoutItemPage(l)
        page.setPageSize('A3')
        l4.pageCollection().addPage(page)
        page = QgsLayoutItemPage(l)
        page.setPageSize('A6')
        l4.pageCollection().addPage(page)

        new_items = l4.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 30), True)
        self.assertEqual(len(new_items), 3)
        new_item1 = [i for i in new_items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in new_items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.pagePositionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.page(), 0)
        self.assertEqual(new_item2.pagePositionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.page(), 0)

        # paste in place, page 2
        new_items = l4.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 550), True)
        self.assertEqual(len(new_items), 3)
        new_item1 = [i for i in new_items if i.id() == 'xxyyxx'][0]
        new_item2 = [i for i in new_items if i.id() == 'zzyyzz'][0]
        self.assertEqual(new_item1.pagePositionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item1.page(), 1)
        self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(new_item2.pagePositionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        self.assertEqual(new_item2.page(), 1)
        self.assertEqual(new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
Example #21
0
    def testStacking(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemPicture(l)
        l.addLayoutItem(item1)
        item2 = QgsLayoutItemPicture(l)
        l.addLayoutItem(item2)
        item3 = QgsLayoutItemPicture(l)
        l.addLayoutItem(item3)

        view = QgsLayoutView()
        view.setCurrentLayout(l)

        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 3)

        # no effect interactions
        view.raiseSelectedItems()
        view.lowerSelectedItems()
        view.moveSelectedItemsToTop()
        view.moveSelectedItemsToBottom()

        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 3)

        # raising
        item3.setSelected(True)
        view.raiseSelectedItems()
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 3)

        item3.setSelected(False)
        item2.setSelected(True)
        view.raiseSelectedItems()
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        view.raiseSelectedItems()
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        item2.setSelected(False)
        item1.setSelected(True)
        view.raiseSelectedItems()
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 1)

        # lower
        item1.setSelected(False)
        item3.setSelected(True)
        view.lowerSelectedItems()
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 1)

        item3.setSelected(False)
        item2.setSelected(True)
        view.lowerSelectedItems()
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 1)

        view.lowerSelectedItems()
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 2)

        # raise to top
        item2.setSelected(False)
        item1.setSelected(True)
        view.moveSelectedItemsToTop()
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 2)

        item1.setSelected(False)
        item3.setSelected(True)
        view.moveSelectedItemsToTop()
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 3)

        item3.setSelected(False)
        item2.setSelected(True)
        view.moveSelectedItemsToTop()
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        # move to bottom
        item2.setSelected(False)
        item1.setSelected(True)
        view.moveSelectedItemsToBottom()
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        item1.setSelected(False)
        item3.setSelected(True)
        view.moveSelectedItemsToBottom()
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 1)

        item3.setSelected(False)
        item2.setSelected(True)
        view.moveSelectedItemsToBottom()
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 2)
Example #22
0
    def testSaveLoadTemplate(self):
        tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt')

        p = QgsProject()
        l = QgsLayout(p)
        l.initializeDefaults()

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        # multiframe
        multiframe1 = QgsLayoutItemHtml(l)
        multiframe1.setHtml('mf1')
        l.addMultiFrame(multiframe1)
        frame1 = QgsLayoutFrame(l, multiframe1)
        frame1.setId('frame1')
        frame1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        frame1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        multiframe1.addFrame(frame1)

        multiframe2 = QgsLayoutItemHtml(l)
        multiframe2.setHtml('mf2')
        l.addMultiFrame(multiframe2)
        frame2 = QgsLayoutFrame(l, multiframe2)
        frame2.setId('frame2')
        frame2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        frame2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        multiframe2.addFrame(frame2)

        uuids = {item1.uuid(), item2.uuid(), frame1.uuid(), frame2.uuid(), multiframe1.uuid(), multiframe2.uuid()}
        original_uuids = {item1.uuid(), item2.uuid(), frame1.uuid(), frame2.uuid()}

        self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        with open(tmpfile) as f:
            template_content = f.read()
        doc = QDomDocument()
        doc.setContent(template_content)

        # adding to existing items
        new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items), 4)
        items = l2.items()
        multiframes = l2.multiFrames()
        self.assertEqual(len(multiframes), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())

        # double check that new items have a unique uid
        self.assertNotIn(new_items[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(multiframes[0].uuid(), [multiframe1.uuid(), multiframe2.uuid()])
        self.assertNotIn(multiframes[1].uuid(), [multiframe1.uuid(), multiframe2.uuid()])
        new_multiframe1 = [i for i in multiframes if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1.layout(), l2)
        new_multiframe2 = [i for i in multiframes if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2.layout(), l2)
        new_frame1 = sip.cast([i for i in items if i.id() == 'frame1'][0], QgsLayoutFrame)
        new_frame2 = sip.cast([i for i in items if i.id() == 'frame2'][0], QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())

        # adding to existing items
        new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items2), 4)
        items = l2.items()
        self.assertEqual(len(items), 8)
        multiframes2 = l2.multiFrames()
        self.assertEqual(len(multiframes2), 4)
        multiframes2 = [m for m in l2.multiFrames() if not m.uuid() in [new_multiframe1.uuid(), new_multiframe2.uuid()]]
        self.assertEqual(len(multiframes2), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())
        self.assertTrue(new_items2[0] in l2.items())
        self.assertTrue(new_items2[1] in l2.items())
        self.assertTrue(new_items2[2] in l2.items())
        self.assertTrue(new_items2[3] in l2.items())
        self.assertNotIn(new_items2[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items2[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items2[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items2[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(multiframes2[0].uuid(), [multiframe1.uuid(), multiframe2.uuid(), new_multiframe1.uuid(), new_multiframe2.uuid()])
        self.assertNotIn(multiframes2[1].uuid(), [multiframe1.uuid(), multiframe2.uuid(), new_multiframe1.uuid(), new_multiframe2.uuid()])

        new_multiframe1b = [i for i in multiframes2 if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1b.layout(), l2)
        new_multiframe2b = [i for i in multiframes2 if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2b.layout(), l2)
        new_frame1b = sip.cast([i for i in items if i.id() == 'frame1' and i.uuid() != new_frame1.uuid()][0], QgsLayoutFrame)
        new_frame2b = sip.cast([i for i in items if i.id() == 'frame2' and i.uuid() != new_frame2.uuid()][0], QgsLayoutFrame)
        self.assertEqual(new_frame1b.multiFrame(), new_multiframe1b)
        self.assertEqual(new_multiframe1b.frames()[0].uuid(), new_frame1b.uuid())
        self.assertEqual(new_frame2b.multiFrame(), new_multiframe2b)
        self.assertEqual(new_multiframe2b.frames()[0].uuid(), new_frame2b.uuid())

        # clearing existing items
        new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True)
        new_multiframes = l2.multiFrames()
        self.assertTrue(ok)
        self.assertEqual(len(new_items3), 5) # includes page
        self.assertEqual(len(new_multiframes), 2)
        items = l2.items()
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'])
        self.assertTrue(new_items3[0] in l2.items())
        self.assertTrue(new_items3[1] in l2.items())
        self.assertTrue(new_items3[2] in l2.items())
        self.assertTrue(new_items3[3] in l2.items())
        new_multiframe1 = [i for i in new_multiframes if i.html() == 'mf1'][0]
        new_multiframe2 = [i for i in new_multiframes if i.html() == 'mf2'][0]

        new_frame1 = sip.cast([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'][0], QgsLayoutFrame)
        new_frame2 = sip.cast([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'][0], QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())
Example #23
0
    def testDistribute(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemPicture(l)
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemPicture(l)
        item2.attemptMove(QgsLayoutPoint(7, 10, QgsUnitTypes.LayoutMillimeters))
        item2.attemptResize(QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item2)
        item3 = QgsLayoutItemPicture(l)
        item3.attemptMove(QgsLayoutPoint(0.8, 1.2, QgsUnitTypes.LayoutCentimeters))
        item3.attemptResize(QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item3)

        view = QgsLayoutView()
        view.setCurrentLayout(l)

        view.distributeSelectedItems(QgsLayoutAligner.DistributeLeft)

        item1.setSelected(True)
        item2.setSelected(True)
        item3.setSelected(True)

        view.distributeSelectedItems(QgsLayoutAligner.DistributeLeft)
        self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item2.positionWithUnits().x(), 6.0, 3)
        self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item3.positionWithUnits().x(), 0.8, 3)
        self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.distributeSelectedItems(QgsLayoutAligner.DistributeHCenter)
        self.assertAlmostEqual(item1.positionWithUnits().x(), 5.0, 3)
        self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item2.positionWithUnits().x(), 6.0, 3)
        self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item3.positionWithUnits().x(), 0.8, 3)
        self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.distributeSelectedItems(QgsLayoutAligner.DistributeRight)
        self.assertAlmostEqual(item1.positionWithUnits().x(), 3.0, 3)
        self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item2.positionWithUnits().x(), 6.0, 3)
        self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item3.positionWithUnits().x(), 0.8, 3)
        self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.distributeSelectedItems(QgsLayoutAligner.DistributeTop)
        self.assertAlmostEqual(item1.positionWithUnits().y(), 8.0, 3)
        self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item2.positionWithUnits().y(), 10.0, 3)
        self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item3.positionWithUnits().y(), 1.2, 3)
        self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.distributeSelectedItems(QgsLayoutAligner.DistributeVCenter)
        self.assertAlmostEqual(item1.positionWithUnits().y(), 8.0, 3)
        self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item2.positionWithUnits().y(), 12.5, 3)
        self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item3.positionWithUnits().y(), 1.2, 3)
        self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))

        view.distributeSelectedItems(QgsLayoutAligner.DistributeBottom)
        self.assertAlmostEqual(item1.positionWithUnits().y(), 8.0, 3)
        self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item2.positionWithUnits().y(), 15.0, 3)
        self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters)
        self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertAlmostEqual(item3.positionWithUnits().y(), 1.2, 3)
        self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters)
        self.assertEqual(item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
Example #24
0
    def testStacking(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemMap(l)
        l.addLayoutItem(item1)
        item2 = QgsLayoutItemMap(l)
        l.addLayoutItem(item2)
        item3 = QgsLayoutItemMap(l)
        l.addLayoutItem(item3)

        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 3)

        # no effect interactions
        self.assertFalse(l.raiseItem(None))
        self.assertFalse(l.lowerItem(None))
        self.assertFalse(l.moveItemToTop(None))
        self.assertFalse(l.moveItemToBottom(None))

        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 3)

        # raising
        self.assertFalse(l.raiseItem(item3))
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 3)

        self.assertTrue(l.raiseItem(item2))
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        self.assertFalse(l.raiseItem(item2))
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        self.assertTrue(l.raiseItem(item1))
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 1)

        # lower
        self.assertFalse(l.lowerItem(item3))
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 1)

        self.assertTrue(l.lowerItem(item2))
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 2)
        self.assertEqual(item3.zValue(), 1)

        self.assertTrue(l.lowerItem(item2))
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 2)

        # raise to top
        self.assertFalse(l.moveItemToTop(item1))
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 2)

        self.assertTrue(l.moveItemToTop(item3))
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 3)

        self.assertTrue(l.moveItemToTop(item2))
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        # move to bottom
        self.assertFalse(l.moveItemToBottom(item1))
        self.assertEqual(item1.zValue(), 1)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 2)

        self.assertTrue(l.moveItemToBottom(item3))
        self.assertEqual(item1.zValue(), 2)
        self.assertEqual(item2.zValue(), 3)
        self.assertEqual(item3.zValue(), 1)

        self.assertTrue(l.moveItemToBottom(item2))
        self.assertEqual(item1.zValue(), 3)
        self.assertEqual(item2.zValue(), 1)
        self.assertEqual(item3.zValue(), 2)
Example #25
0
    def testThemeChanged(self):
        """
        Test that the mapTheme(s)Changed signals are correctly emitted in all relevant situations
        """
        project = QgsProject()
        collection = QgsMapThemeCollection(project)

        record = QgsMapThemeCollection.MapThemeRecord()

        theme_changed_spy = QSignalSpy(collection.mapThemeChanged)
        themes_changed_spy = QSignalSpy(collection.mapThemesChanged)

        collection.insert('theme1', record)
        self.assertEqual(len(theme_changed_spy), 1)
        self.assertEqual(theme_changed_spy[-1][0], 'theme1')
        self.assertEqual(len(themes_changed_spy), 1)

        # reinsert
        collection.insert('theme1', record)
        self.assertEqual(len(theme_changed_spy), 2)
        self.assertEqual(theme_changed_spy[-1][0], 'theme1')
        self.assertEqual(len(themes_changed_spy), 2)

        # update
        collection.update('theme1', record)
        self.assertEqual(len(theme_changed_spy), 3)
        self.assertEqual(theme_changed_spy[-1][0], 'theme1')
        self.assertEqual(len(themes_changed_spy), 3)

        # remove invalid
        collection.removeMapTheme(
            'i wish i was a slave to an age old trade... like riding around on rail cars and working long days'
        )
        self.assertEqual(len(theme_changed_spy), 3)
        self.assertEqual(len(themes_changed_spy), 3)
        # remove valid
        collection.removeMapTheme('theme1')
        self.assertEqual(len(theme_changed_spy), 3)  # not changed - removed!
        self.assertEqual(len(themes_changed_spy), 4)

        # reinsert
        collection.insert('theme1', record)
        self.assertEqual(len(theme_changed_spy), 4)
        self.assertEqual(len(themes_changed_spy), 5)

        # clear
        collection.clear()
        self.assertEqual(len(theme_changed_spy), 4)  # not changed - removed!
        self.assertEqual(len(themes_changed_spy), 6)

        # check that mapThemeChanged is emitted if layer is removed
        layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory")
        layer2 = QgsVectorLayer("Point?field=fldtxt:string", "layer2",
                                "memory")
        project.addMapLayers([layer, layer2])

        # record for layer1
        record.addLayerRecord(QgsMapThemeCollection.MapThemeLayerRecord(layer))
        collection.insert('theme1', record)
        self.assertEqual(len(theme_changed_spy), 5)
        self.assertEqual(len(themes_changed_spy), 7)

        # now kill layer 2
        project.removeMapLayer(layer2)
        self.assertEqual(
            len(theme_changed_spy),
            5)  # signal should not be emitted - layer is not in record
        # now kill layer 1
        project.removeMapLayer(layer)
        app.processEvents()
        self.assertEqual(len(theme_changed_spy),
                         6)  # signal should be emitted - layer is in record
Example #26
0
    def testResize(self):
        p = QgsProject()
        l = QgsLayout(p)

        # add some items
        item1 = QgsLayoutItemPicture(l)
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(
            QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemPicture(l)
        item2.attemptMove(QgsLayoutPoint(7, 10,
                                         QgsUnitTypes.LayoutMillimeters))
        item2.attemptResize(
            QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item2)
        item3 = QgsLayoutItemPicture(l)
        item3.attemptMove(
            QgsLayoutPoint(0.8, 1.2, QgsUnitTypes.LayoutCentimeters))
        item3.attemptResize(
            QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item3)

        QgsLayoutAligner.resizeItems(l, [item1, item2, item3],
                                     QgsLayoutAligner.ResizeNarrowest)
        self.assertEqual(item1.sizeWithUnits(),
                         QgsLayoutSize(10, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(),
                         QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(
            item3.sizeWithUnits(),
            QgsLayoutSize(1.0, 1.6, QgsUnitTypes.LayoutCentimeters))
        l.undoStack().stack().undo()

        QgsLayoutAligner.resizeItems(l, [item1, item2, item3],
                                     QgsLayoutAligner.ResizeWidest)
        self.assertEqual(item1.sizeWithUnits(),
                         QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(),
                         QgsLayoutSize(18, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(
            item3.sizeWithUnits(),
            QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
        l.undoStack().stack().undo()

        QgsLayoutAligner.resizeItems(l, [item1, item2, item3],
                                     QgsLayoutAligner.ResizeShortest)
        self.assertEqual(item1.sizeWithUnits(),
                         QgsLayoutSize(18, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(),
                         QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(
            item3.sizeWithUnits(),
            QgsLayoutSize(1.8, 0.9, QgsUnitTypes.LayoutCentimeters))
        l.undoStack().stack().undo()

        QgsLayoutAligner.resizeItems(l, [item1, item2, item3],
                                     QgsLayoutAligner.ResizeTallest)
        self.assertEqual(item1.sizeWithUnits(),
                         QgsLayoutSize(18, 16, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(),
                         QgsLayoutSize(10, 16, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(
            item3.sizeWithUnits(),
            QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
        l.undoStack().stack().undo()

        item2.attemptResize(
            QgsLayoutSize(10, 19, QgsUnitTypes.LayoutMillimeters))
        QgsLayoutAligner.resizeItems(l, [item1, item2, item3],
                                     QgsLayoutAligner.ResizeToSquare)
        self.assertEqual(item1.sizeWithUnits(),
                         QgsLayoutSize(18, 18, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(item2.sizeWithUnits(),
                         QgsLayoutSize(19, 19, QgsUnitTypes.LayoutMillimeters))
        self.assertEqual(
            item3.sizeWithUnits(),
            QgsLayoutSize(1.8, 1.8, QgsUnitTypes.LayoutCentimeters))

        l.undoStack().stack().undo()
        QgsLayoutAligner.resizeItems(l, [item1],
                                     QgsLayoutAligner.ResizeToSquare)
        self.assertEqual(item1.sizeWithUnits(),
                         QgsLayoutSize(18, 18, QgsUnitTypes.LayoutMillimeters))
Example #27
0
 def testLayout(self):
     # test that layouts have a collection
     p = QgsProject()
     l = QgsLayout(p)
     self.assertTrue(l.pageCollection())
     self.assertEqual(l.pageCollection().layout(), l)
Example #28
0
    def testIteration(self):
        p = QgsProject()
        vectorFileInfo = QFileInfo(unitTestDataPath() + "/france_parts.shp")
        vector_layer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")
        self.assertTrue(vector_layer.isValid())
        p.addMapLayer(vector_layer)

        l = QgsPrintLayout(p)
        atlas = l.atlas()
        atlas.setEnabled(True)
        atlas.setCoverageLayer(vector_layer)

        atlas_feature_changed_spy = QSignalSpy(atlas.featureChanged)
        context_changed_spy = QSignalSpy(l.reportContext().changed)

        self.assertTrue(atlas.beginRender())
        self.assertTrue(atlas.first())
        self.assertEqual(len(atlas_feature_changed_spy), 1)
        self.assertEqual(len(context_changed_spy), 1)
        self.assertEqual(atlas.currentFeatureNumber(), 0)
        self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie')
        self.assertEqual(l.reportContext().layer(), vector_layer)
        f1 = l.reportContext().feature()

        self.assertTrue(atlas.next())
        self.assertEqual(len(atlas_feature_changed_spy), 2)
        self.assertEqual(len(context_changed_spy), 2)
        self.assertEqual(atlas.currentFeatureNumber(), 1)
        self.assertEqual(l.reportContext().feature()[4], 'Bretagne')
        f2 = l.reportContext().feature()

        self.assertTrue(atlas.next())
        self.assertEqual(len(atlas_feature_changed_spy), 3)
        self.assertEqual(len(context_changed_spy), 3)
        self.assertEqual(atlas.currentFeatureNumber(), 2)
        self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire')
        f3 = l.reportContext().feature()

        self.assertTrue(atlas.next())
        self.assertEqual(len(atlas_feature_changed_spy), 4)
        self.assertEqual(len(context_changed_spy), 4)
        self.assertEqual(atlas.currentFeatureNumber(), 3)
        self.assertEqual(l.reportContext().feature()[4], 'Centre')
        f4 = l.reportContext().feature()

        self.assertFalse(atlas.next())
        self.assertTrue(atlas.seekTo(2))
        self.assertEqual(len(atlas_feature_changed_spy), 5)
        self.assertEqual(len(context_changed_spy), 5)
        self.assertEqual(atlas.currentFeatureNumber(), 2)
        self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire')

        self.assertTrue(atlas.last())
        self.assertEqual(len(atlas_feature_changed_spy), 6)
        self.assertEqual(len(context_changed_spy), 6)
        self.assertEqual(atlas.currentFeatureNumber(), 3)
        self.assertEqual(l.reportContext().feature()[4], 'Centre')

        self.assertTrue(atlas.previous())
        self.assertEqual(len(atlas_feature_changed_spy), 7)
        self.assertEqual(len(context_changed_spy), 7)
        self.assertEqual(atlas.currentFeatureNumber(), 2)
        self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire')

        self.assertTrue(atlas.previous())
        self.assertTrue(atlas.previous())
        self.assertEqual(len(atlas_feature_changed_spy), 9)
        self.assertFalse(atlas.previous())
        self.assertEqual(len(atlas_feature_changed_spy), 9)

        self.assertTrue(atlas.endRender())
        self.assertEqual(len(atlas_feature_changed_spy), 10)

        self.assertTrue(atlas.seekTo(f1))
        self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie')
        self.assertTrue(atlas.seekTo(f4))
        self.assertEqual(l.reportContext().feature()[4], 'Centre')
        self.assertTrue(atlas.seekTo(f3))
        self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire')
        self.assertTrue(atlas.seekTo(f2))
        self.assertEqual(l.reportContext().feature()[4], 'Bretagne')
        self.assertFalse(atlas.seekTo(QgsFeature(5)))
Example #29
0
    def testPages(self):
        """
        Test adding/retrieving/deleting pages from the collection
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        self.assertEqual(collection.pageCount(), 0)
        self.assertFalse(collection.pages())
        self.assertFalse(collection.page(-1))
        self.assertFalse(collection.page(0))
        self.assertFalse(collection.page(1))

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        self.assertEqual(collection.pageNumber(page), -1)

        collection.addPage(page)

        self.assertTrue(page in l.items())

        self.assertEqual(collection.pageCount(), 1)
        self.assertEqual(collection.pages(), [page])
        self.assertFalse(collection.page(-1))
        self.assertEqual(collection.page(0), page)
        self.assertFalse(collection.page(1))
        self.assertEqual(collection.pageNumber(page), 0)

        # add a second page
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        self.assertEqual(collection.pageCount(), 2)
        self.assertEqual(collection.pages(), [page, page2])
        self.assertFalse(collection.page(-1))
        self.assertEqual(collection.page(0), page)
        self.assertEqual(collection.page(1), page2)
        self.assertEqual(collection.pageNumber(page2), 1)

        # insert a page
        page3 = QgsLayoutItemPage(l)
        page3.setPageSize('A3')
        collection.insertPage(page3, 1)
        self.assertTrue(page3 in l.items())

        self.assertEqual(collection.pageCount(), 3)
        self.assertEqual(collection.pages(), [page, page3, page2])
        self.assertEqual(collection.page(0), page)
        self.assertEqual(collection.page(1), page3)
        self.assertEqual(collection.page(2), page2)
        self.assertEqual(collection.pageNumber(page3), 1)

        # delete page
        collection.deletePage(-1)
        self.assertEqual(collection.pageCount(), 3)
        self.assertEqual(collection.pages(), [page, page3, page2])
        collection.deletePage(100)
        self.assertEqual(collection.pageCount(), 3)
        self.assertEqual(collection.pages(), [page, page3, page2])
        collection.deletePage(1)
        self.assertEqual(collection.pageCount(), 2)
        self.assertEqual(collection.pages(), [page, page2])

        # make sure page was deleted
        QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
        self.assertTrue(sip.isdeleted(page3))

        del l
        QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
        self.assertTrue(sip.isdeleted(page))
        self.assertTrue(sip.isdeleted(page2))
Example #30
0
    def testSaveLoadProject(self):

        schema_uri = encode_uri(self.ds_uri, 'qgis_test')
        project_uri = encode_uri(self.ds_uri, 'qgis_test', 'abc')

        self.dropProjectsTable()  # make sure we have a clean start

        prj = QgsProject()
        uri = self.vl.source()
        vl1 = QgsVectorLayer(uri, 'test', 'postgres')
        self.assertEqual(vl1.isValid(), True)
        prj.addMapLayer(vl1)

        prj_storage = QgsApplication.projectStorageRegistry(
        ).projectStorageFromType("postgresql")
        self.assertTrue(prj_storage)

        lst0 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst0, [])

        # try to save project in the database

        prj.setFileName(project_uri)
        res = prj.write()
        self.assertTrue(res)

        lst1 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst1, ["abc"])

        # now try to load the project back

        prj2 = QgsProject()
        prj2.setFileName(project_uri)
        res = prj2.read()
        self.assertTrue(res)

        self.assertEqual(len(prj2.mapLayers()), 1)

        self.assertEqual(prj2.baseName(), "abc")
        self.assertEqual(prj2.absoluteFilePath(),
                         "")  # path not supported for project storages
        self.assertTrue(
            abs(prj2.lastModified().secsTo(QDateTime.currentDateTime())) < 10)

        # try to see project's metadata

        res, metadata = prj_storage.readProjectStorageMetadata(project_uri)
        self.assertTrue(res)
        self.assertEqual(metadata.name, "abc")
        time_project = metadata.lastModified
        time_now = QDateTime.currentDateTime()
        time_diff = time_now.secsTo(time_project)
        self.assertTrue(abs(time_diff) < 10)

        # try to remove the project

        res = prj_storage.removeProject(project_uri)
        self.assertTrue(res)

        lst2 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst2, [])

        self.dropProjectsTable(
        )  # make sure we have a clean finish... "leave no trace"