Ejemplo n.º 1
0
    def test_zip_unzip(self):
        tmpDir = QTemporaryDir()
        tmpFile = "{}/project.qgz".format(tmpDir.path())

        project = QgsProject()

        l0 = QgsVectorLayer(os.path.join(TEST_DATA_DIR, "points.shp"), "points", "ogr")
        l1 = QgsVectorLayer(os.path.join(TEST_DATA_DIR, "lines.shp"), "lines", "ogr")
        project.addMapLayers([l0, l1])

        self.assertTrue(project.write(tmpFile))

        project2 = QgsProject()
        self.assertFalse(project2.isZipped())
        self.assertTrue(project2.fileName() == "")
        self.assertTrue(project2.read(tmpFile))
        self.assertTrue(project2.isZipped())
        self.assertTrue(project2.fileName() == tmpFile)
        layers = project2.mapLayers()

        self.assertEqual(len(layers.keys()), 2)
        self.assertTrue(layers[l0.id()].isValid(), True)
        self.assertTrue(layers[l1.id()].isValid(), True)

        project2.clear()
        self.assertFalse(project2.isZipped())
Ejemplo n.º 2
0
    def testProjectStyle(self):
        project = QgsProject()
        settings = project.styleSettings()
        self.assertIsInstance(settings.projectStyle(), QgsStyle)
        self.assertEqual(settings.projectStyle().name(), 'Project Styles')

        text_format = QgsTextFormat()
        text_format.setColor(QColor(255, 0, 0))
        self.assertTrue(settings.projectStyle().addTextFormat(
            'my text format', text_format))
        self.assertTrue(settings.projectStyle().saveTextFormat(
            'my text format', text_format, True, []))
        self.assertEqual(settings.projectStyle().textFormatCount(), 1)

        tmp_dir = QTemporaryDir()
        tmp_project_file = "{}/project.qgs".format(tmp_dir.path())
        self.assertTrue(project.write(tmp_project_file))

        project.deleteLater()
        del project
        QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)

        project2 = QgsProject()
        self.assertTrue(project2.read(tmp_project_file))
        self.assertEqual(
            project2.styleSettings().projectStyle().textFormatCount(), 1)
        self.assertEqual(
            project2.styleSettings().projectStyle().textFormat(
                'my text format').color().name(), '#ff0000')

        project2.clear()
        self.assertEqual(
            project2.styleSettings().projectStyle().textFormatCount(), 0)
Ejemplo n.º 3
0
    def testSaveRestoreFromProject(self):
        p = QgsProject()
        provider = ProjectProvider(p)

        # add some algorithms
        alg = QgsProcessingModelAlgorithm('test name', 'test group')
        provider.add_model(alg)
        alg2 = QgsProcessingModelAlgorithm('test name2', 'test group2')
        provider.add_model(alg2)
        self.assertEqual(len(provider.algorithms()), 2)

        tmp_file = QTemporaryFile()
        tmp_file.open()  # fileName is no available until open
        temp_path = tmp_file.fileName()
        tmp_file.close()

        self.assertTrue(p.write(temp_path))

        # restore project
        p2 = QgsProject()
        provider2 = ProjectProvider(p2)
        self.assertTrue(p2.read(temp_path))

        self.assertEqual(len(provider2.model_definitions), 2)
        self.assertEqual(len(provider2.algorithms()), 2)
        self.assertEqual(provider2.algorithms()[0].name(), 'test name')
        self.assertEqual(provider2.algorithms()[0].group(), 'test group')
        self.assertEqual(provider2.algorithms()[1].name(), 'test name2')
        self.assertEqual(provider2.algorithms()[1].group(), 'test group2')

        # clear project should remove algorithms
        p2.clear()
        self.assertFalse(provider2.algorithms())
Ejemplo n.º 4
0
    def test_zip_unzip(self):
        tmpDir = QTemporaryDir()
        tmpFile = "{}/project.qgz".format(tmpDir.path())

        project = QgsProject()

        l0 = QgsVectorLayer(os.path.join(TEST_DATA_DIR, "points.shp"), "points", "ogr")
        l1 = QgsVectorLayer(os.path.join(TEST_DATA_DIR, "lines.shp"), "lines", "ogr")
        project.addMapLayers([l0, l1])

        self.assertTrue(project.write(tmpFile))

        project2 = QgsProject()
        self.assertFalse(project2.isZipped())
        self.assertTrue(project2.fileName() == "")
        self.assertTrue(project2.read(tmpFile))
        self.assertTrue(project2.isZipped())
        self.assertTrue(project2.fileName() == tmpFile)
        layers = project2.mapLayers()

        self.assertEqual(len(layers.keys()), 2)
        self.assertTrue(layers[l0.id()].isValid(), True)
        self.assertTrue(layers[l1.id()].isValid(), True)

        project2.clear()
        self.assertFalse(project2.isZipped())
Ejemplo n.º 5
0
    def testProjectMainAnnotationLayer(self):
        p = QgsProject()
        self.assertIsNotNone(p.mainAnnotationLayer())

        # add some items to project annotation layer
        polygon_item_id = p.mainAnnotationLayer().addItem(QgsAnnotationPolygonItem(
            QgsPolygon(QgsLineString([QgsPoint(12, 13), QgsPoint(14, 13), QgsPoint(14, 15), QgsPoint(12, 13)]))))
        linestring_item_id = p.mainAnnotationLayer().addItem(
            QgsAnnotationLineItem(QgsLineString([QgsPoint(11, 13), QgsPoint(12, 13), QgsPoint(12, 15)])))
        marker_item_id = p.mainAnnotationLayer().addItem(QgsAnnotationMarkerItem(QgsPoint(12, 13)))

        # save project to xml
        tmpDir = QTemporaryDir()
        tmpFile = "{}/project.qgs".format(tmpDir.path())
        self.assertTrue(p.write(tmpFile))

        # test that annotation layer is cleared with project
        p.clear()
        self.assertEqual(len(p.mainAnnotationLayer().items()), 0)

        # check that main annotation layer is restored on project read
        p2 = QgsProject()
        self.assertTrue(p2.read(tmpFile))
        self.assertEqual(len(p2.mainAnnotationLayer().items()), 3)
        self.assertIsInstance(p2.mainAnnotationLayer().items()[polygon_item_id], QgsAnnotationPolygonItem)
        self.assertIsInstance(p2.mainAnnotationLayer().items()[linestring_item_id], QgsAnnotationLineItem)
        self.assertIsInstance(p2.mainAnnotationLayer().items()[marker_item_id], QgsAnnotationMarkerItem)
Ejemplo n.º 6
0
    def testCustomLayerOrder(self):
        """ test project layer order"""
        prj = QgsProject()
        layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory")
        layer2 = QgsVectorLayer("Point?field=fldtxt:string", "layer2",
                                "memory")
        layer3 = QgsVectorLayer("Point?field=fldtxt:string", "layer3",
                                "memory")
        prj.addMapLayers([layer, layer2, layer3])

        layer_order_changed_spy = QSignalSpy(
            prj.layerTreeRoot().customLayerOrderChanged)
        prj.layerTreeRoot().setCustomLayerOrder([layer2, layer])
        self.assertEqual(len(layer_order_changed_spy), 1)
        prj.layerTreeRoot().setCustomLayerOrder([layer2, layer])
        self.assertEqual(len(layer_order_changed_spy),
                         1)  # no signal, order not changed

        self.assertEqual(prj.layerTreeRoot().customLayerOrder(),
                         [layer2, layer])
        prj.layerTreeRoot().setCustomLayerOrder([layer])
        self.assertEqual(prj.layerTreeRoot().customLayerOrder(), [layer])
        self.assertEqual(len(layer_order_changed_spy), 2)

        # remove a layer
        prj.layerTreeRoot().setCustomLayerOrder([layer2, layer, layer3])
        self.assertEqual(len(layer_order_changed_spy), 3)
        prj.removeMapLayer(layer)
        self.assertEqual(prj.layerTreeRoot().customLayerOrder(),
                         [layer2, layer3])
        self.assertEqual(len(layer_order_changed_spy), 4)

        # save and restore
        file_name = os.path.join(QDir.tempPath(), 'proj.qgs')
        prj.setFileName(file_name)
        prj.write()
        prj2 = QgsProject()
        prj2.setFileName(file_name)
        prj2.read()
        self.assertEqual(
            [l.id() for l in prj2.layerTreeRoot().customLayerOrder()],
            [layer2.id(), layer3.id()])

        # clear project
        prj.clear()
        self.assertEqual(prj.layerTreeRoot().customLayerOrder(), [])
Ejemplo n.º 7
0
def transactional_project(iface,
                          src_url=None,
                          dest_url=None,
                          dont_resolve_layers=True):
    """Context manager returning a ``QgsProject`` instance and saves it on exit
    if no error occured.

    If ``src_url`` is ``None``, the returned project is the current one (the
    one loaded int QGIS interface). Else, the project found at ``src_url`` is
    returned.

    The project is saved to its original location if ``dest_url`` is ``None``,
    else it is saved to ``dest_url``.

    Implementation detail: after saving the project with ``proj.write()`` (thus
    updating the project file on disk), when the user clicks on the Save icon
    in QGIS UI, a warning is shown indicating that the file has been modified
    after it has been opened by QGIS. Workaround: the project is reloaded with
    ``proj.clear()`` and ``proj.read()``.
    """
    try:
        if src_url:
            proj = QgsProject()
            if dont_resolve_layers:
                proj.read(src_url, QgsProject.FlagDontResolveLayers)
            else:
                proj.read(src_url)
        else:
            proj = QgsProject.instance()
        yield proj
    except Exception as exc:
        log_exception(exc, level='Critical', feedback=True, iface=iface)
    finally:
        if not dest_url:
            project_saved = proj.write()
            dest_url = proj.fileName()
        else:
            project_saved = proj.write(dest_url)
        if not project_saved:
            log_message('Project has not been saved after transaction.',
                        level='Warning',
                        feedback=True,
                        iface=iface)
        # XXX: better way to avoid warning if the user click save ?
        proj.clear()
        proj.read(dest_url)
Ejemplo n.º 8
0
    def testProject(self):
        p = QgsProject()
        m = self.createTestMetadata()

        metadata_changed_spy = QSignalSpy(p.metadataChanged)
        p.setMetadata(m)
        self.assertEqual(len(metadata_changed_spy), 1)
        self.checkExpectedMetadata(p.metadata())

        p.clear()
        self.assertEqual(len(metadata_changed_spy), 2)
        self.assertEqual(p.metadata().title(), '')

        # test that the project title is just a shortcut to the metadata title field
        p.setTitle('my title')
        self.assertEqual(p.metadata().title(), 'my title')
        m.setTitle('my title 2')
        p.setMetadata(m)
        self.assertEqual(p.title(), 'my title 2')
Ejemplo n.º 9
0
    def testProject(self):
        p = QgsProject()
        m = self.createTestMetadata()

        metadata_changed_spy = QSignalSpy(p.metadataChanged)
        p.setMetadata(m)
        self.assertEqual(len(metadata_changed_spy), 1)
        self.checkExpectedMetadata(p.metadata())

        p.clear()
        self.assertEqual(len(metadata_changed_spy), 2)
        self.assertEqual(p.metadata().title(), '')

        # test that the project title is just a shortcut to the metadata title field
        p.setTitle('my title')
        self.assertEqual(p.metadata().title(), 'my title')
        m.setTitle('my title 2')
        p.setMetadata(m)
        self.assertEqual(p.title(), 'my title 2')
Ejemplo n.º 10
0
    def testCustomLayerOrder(self):
        """ test project layer order"""
        prj = QgsProject()
        layer = QgsVectorLayer("Point?field=fldtxt:string",
                               "layer1", "memory")
        layer2 = QgsVectorLayer("Point?field=fldtxt:string",
                                "layer2", "memory")
        layer3 = QgsVectorLayer("Point?field=fldtxt:string",
                                "layer3", "memory")
        prj.addMapLayers([layer, layer2, layer3])

        layer_order_changed_spy = QSignalSpy(prj.layerTreeRoot().customLayerOrderChanged)
        prj.layerTreeRoot().setCustomLayerOrder([layer2, layer])
        self.assertEqual(len(layer_order_changed_spy), 1)
        prj.layerTreeRoot().setCustomLayerOrder([layer2, layer])
        self.assertEqual(len(layer_order_changed_spy), 1) # no signal, order not changed

        self.assertEqual(prj.layerTreeRoot().customLayerOrder(), [layer2, layer])
        prj.layerTreeRoot().setCustomLayerOrder([layer])
        self.assertEqual(prj.layerTreeRoot().customLayerOrder(), [layer])
        self.assertEqual(len(layer_order_changed_spy), 2)

        # remove a layer
        prj.layerTreeRoot().setCustomLayerOrder([layer2, layer, layer3])
        self.assertEqual(len(layer_order_changed_spy), 3)
        prj.removeMapLayer(layer)
        self.assertEqual(prj.layerTreeRoot().customLayerOrder(), [layer2, layer3])
        self.assertEqual(len(layer_order_changed_spy), 4)

        # save and restore
        file_name = os.path.join(QDir.tempPath(), 'proj.qgs')
        prj.setFileName(file_name)
        prj.write()
        prj2 = QgsProject()
        prj2.setFileName(file_name)
        prj2.read()
        self.assertEqual([l.id() for l in prj2.layerTreeRoot().customLayerOrder()], [layer2.id(), layer3.id()])

        # clear project
        prj.clear()
        self.assertEqual(prj.layerTreeRoot().customLayerOrder(), [])