示例#1
0
    def testRectangle(self):
        rect = QgsReferencedRectangle(QgsRectangle(0.0, 1.0, 20.0, 10.0), QgsCoordinateReferenceSystem('epsg:3111'))
        self.assertEqual(rect.xMinimum(), 0.0)
        self.assertEqual(rect.yMinimum(), 1.0)
        self.assertEqual(rect.xMaximum(), 20.0)
        self.assertEqual(rect.yMaximum(), 10.0)
        self.assertEqual(rect.crs().authid(), 'EPSG:3111')

        rect.setCrs(QgsCoordinateReferenceSystem('epsg:28356'))
        self.assertEqual(rect.crs().authid(), 'EPSG:28356')

        # in variant
        v = QVariant(QgsReferencedRectangle(QgsRectangle(1.0, 2.0, 3.0, 4.0), QgsCoordinateReferenceSystem('epsg:3111')))
        self.assertEqual(v.value().xMinimum(), 1.0)
        self.assertEqual(v.value().yMinimum(), 2.0)
        self.assertEqual(v.value().xMaximum(), 3.0)
        self.assertEqual(v.value().yMaximum(), 4.0)
        self.assertEqual(v.value().crs().authid(), 'EPSG:3111')

        # to rectangle
        r = QgsRectangle(rect)
        self.assertEqual(r.xMinimum(), 0.0)
        self.assertEqual(r.yMinimum(), 1.0)
        self.assertEqual(r.xMaximum(), 20.0)
        self.assertEqual(r.yMaximum(), 10.0)

        # test that QgsReferencedRectangle IS a QgsRectangle
        r2 = QgsRectangle(5, 6, 30, 40)
        r2.combineExtentWith(rect)
        self.assertEqual(r2.xMinimum(), 0.0)
        self.assertEqual(r2.yMinimum(), 1.0)
        self.assertEqual(r2.xMaximum(), 30.0)
        self.assertEqual(r2.yMaximum(), 40.0)
    def testExportImport(self):
        p = QgsProject()
        manager = QgsBookmarkManager.createProjectBasedManager(p)
        manager2 = QgsBookmarkManager.createProjectBasedManager(p)
        manager3 = QgsBookmarkManager.createProjectBasedManager(p)

        tmpDir = QTemporaryDir()
        tmpFile = "{}/bookmarks.xml".format(tmpDir.path())

        # no managers
        self.assertTrue(QgsBookmarkManager.exportToFile(tmpFile, []))
        self.assertTrue(manager3.importFromFile(tmpFile))
        self.assertFalse(manager3.bookmarks())

        # no bookmarks
        self.assertTrue(QgsBookmarkManager.exportToFile(tmpFile, [manager]))
        self.assertTrue(manager3.importFromFile(tmpFile))
        self.assertFalse(manager3.bookmarks())

        # add a bunch of bookmarks
        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        manager.addBookmark(b2)
        manager2.addBookmark(b3)

        # export one manager's bookmarks
        self.assertTrue(QgsBookmarkManager.exportToFile(tmpFile, [manager]))
        self.assertTrue(manager3.importFromFile(tmpFile))
        self.assertEqual([(b.name(), b.extent())
                          for b in manager3.bookmarks()],
                         [(b.name(), b.extent()) for b in [b, b2]])

        manager3.clear()
        # export both manager's bookmarks
        self.assertTrue(
            QgsBookmarkManager.exportToFile(tmpFile, [manager, manager2]))
        self.assertTrue(manager3.importFromFile(tmpFile))
        self.assertEqual([(b.name(), b.extent())
                          for b in manager3.bookmarks()],
                         [(b.name(), b.extent()) for b in [b, b2, b3]])
    def testBookmarksById(self):
        project = QgsProject()
        manager = QgsBookmarkManager.createProjectBasedManager(project)

        # add a bunch of bookmarks
        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        manager.addBookmark(b2)
        manager.addBookmark(b3)

        self.assertFalse(manager.bookmarkById('asdf').name())
        self.assertEqual(manager.bookmarkById('1'), b)
        self.assertEqual(manager.bookmarkById('2'), b2)
        self.assertEqual(manager.bookmarkById('3'), b3)
    def testBookmarks(self):
        project = QgsProject()
        manager = QgsBookmarkManager.createProjectBasedManager(project)

        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        self.assertEqual(manager.bookmarks(), [b])
        manager.addBookmark(b2)
        self.assertEqual(manager.bookmarks(), [b, b2])
        manager.addBookmark(b3)
        self.assertEqual(manager.bookmarks(), [b, b2, b3])
示例#5
0
    def testReadWrite(self):
        p = QgsProjectViewSettings()
        self.assertFalse(p.mapScales())
        self.assertFalse(p.useProjectScales())
        doc = QDomDocument("testdoc")
        elem = p.writeXml(doc, QgsReadWriteContext())

        p2 = QgsProjectViewSettings()
        spy = QSignalSpy(p2.mapScalesChanged)
        self.assertTrue(p2.readXml(elem, QgsReadWriteContext()))
        self.assertFalse(p2.mapScales())
        self.assertFalse(p2.useProjectScales())
        self.assertEqual(len(spy), 0)
        self.assertTrue(p2.defaultViewExtent().isNull())

        p.setUseProjectScales(True)
        p.setMapScales([56, 78, 99])
        p.setDefaultViewExtent(QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4), QgsCoordinateReferenceSystem("EPSG:3857")))
        elem = p.writeXml(doc, QgsReadWriteContext())

        p2 = QgsProjectViewSettings()
        spy = QSignalSpy(p2.mapScalesChanged)
        self.assertTrue(p2.readXml(elem, QgsReadWriteContext()))
        self.assertEqual(p2.mapScales(), [99.0, 78.0, 56.0])
        self.assertTrue(p2.useProjectScales())
        self.assertEqual(len(spy), 1)
        self.assertEqual(p2.defaultViewExtent(), QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4), QgsCoordinateReferenceSystem("EPSG:3857")))
    def testFileStorage(self):
        """
        Test file bound manager
        """
        manager = QgsBookmarkManager()

        tmpDir = QTemporaryDir()
        tmpFile = "{}/bookmarks.xml".format(tmpDir.path())

        manager.initialize(tmpFile)

        # add a bunch of bookmarks
        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        manager.addBookmark(b2)
        manager.addBookmark(b3)

        # destroy manager, causes write to disk
        manager.deleteLater()
        QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
        del manager

        # create another new manager with same key, should contain existing bookmarks
        manager2 = QgsBookmarkManager()
        self.assertFalse(manager2.bookmarks())
        manager2.initialize(tmpFile)
        self.assertEqual(manager2.bookmarks(), [b, b2, b3])

        # but a manager with a different key should not...
        tmpFile2 = "{}/bookmarks2.xml".format(tmpDir.path())
        manager3 = QgsBookmarkManager()
        manager3.initialize(tmpFile2)
        self.assertEqual(manager3.bookmarks(), [])
    def testAddBookmark(self):
        project = QgsProject()
        b = QgsBookmark()
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                   QgsCoordinateReferenceSystem('EPSG:3111')))

        manager = QgsBookmarkManager.createProjectBasedManager(project)

        bookmark_about_to_be_added_spy = QSignalSpy(
            manager.bookmarkAboutToBeAdded)
        bookmark_added_spy = QSignalSpy(manager.bookmarkAdded)
        id, res = manager.addBookmark(b)
        self.assertTrue(res)
        self.assertEqual(len(bookmark_about_to_be_added_spy), 1)
        self.assertEqual(bookmark_about_to_be_added_spy[0][0], id)
        self.assertEqual(len(bookmark_added_spy), 1)
        self.assertEqual(bookmark_added_spy[0][0], id)

        b = manager.bookmarkById(id)
        self.assertEqual(b.name(), 'b1')
        self.assertEqual(
            b.extent(),
            QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                   QgsCoordinateReferenceSystem('EPSG:3111')))

        # adding it again should fail
        id, res = manager.addBookmark(b)
        self.assertFalse(res)

        # try adding a second bookmark
        b2 = QgsBookmark()
        b2.setId('my id')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        id2, res = manager.addBookmark(b2)
        self.assertTrue(res)
        self.assertEqual(id2, 'my id')
        self.assertEqual(len(bookmark_added_spy), 2)
        self.assertEqual(bookmark_about_to_be_added_spy[1][0], 'my id')
        self.assertEqual(len(bookmark_about_to_be_added_spy), 2)
        self.assertEqual(bookmark_added_spy[1][0], 'my id')

        # adding a bookmark with duplicate id should fail
        b3 = QgsBookmark()
        b3.setId('my id')

        id, res = manager.addBookmark(b3)
        self.assertFalse(res)
示例#8
0
    def testDefaultViewExtent(self):
        p = QgsProjectViewSettings()
        self.assertTrue(p.defaultViewExtent().isNull())

        p.setDefaultViewExtent(QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4), QgsCoordinateReferenceSystem("EPSG:3857")))
        self.assertEqual(p.defaultViewExtent(), QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4), QgsCoordinateReferenceSystem("EPSG:3857")))

        p.setDefaultViewExtent(QgsReferencedRectangle())
        self.assertTrue(p.defaultViewExtent().isNull())

        p.setDefaultViewExtent(QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4), QgsCoordinateReferenceSystem("EPSG:3857")))
        p.reset()
        self.assertTrue(p.defaultViewExtent().isNull())
示例#9
0
    def test_visible_features(self):
        """
        Test filtering to visible features only
        """
        layer_path = os.path.join(os.path.dirname(__file__), 'test_layer.shp')

        vl1 = QgsVectorLayer(layer_path, 'test_layer', 'ogr')
        vl1.setSubsetString('id < 10')
        self.assertTrue(vl1.isValid())
        QgsProject.instance().addMapLayer(vl1)

        # not using visible features
        settings = PlotSettings('scatter')
        settings.source_layer_id = vl1.id()

        settings.properties['x_name'] = 'so4'
        settings.properties['y_name'] = 'ca'

        rect = QgsReferencedRectangle(QgsRectangle(10.1, 43.5, 10.8, 43.85),
                                      QgsCoordinateReferenceSystem(4326))
        factory = PlotFactory(settings, visible_region=rect)
        spy = QSignalSpy(factory.plot_built)
        self.assertEqual(len(spy), 0)
        self.assertEqual(factory.settings.x,
                         [98, 88, 267, 329, 319, 137, 350, 151, 203])
        self.assertEqual(factory.settings.y, [
            81.87, 22.26, 74.16, 35.05, 46.64, 126.73, 116.44, 108.25, 110.45
        ])

        settings.properties['visible_features_only'] = True
        factory = PlotFactory(settings, visible_region=rect)
        spy = QSignalSpy(factory.plot_built)
        self.assertEqual(factory.settings.x, [88, 350, 151, 203])
        self.assertEqual(factory.settings.y, [22.26, 116.44, 108.25, 110.45])

        factory.set_visible_region(
            QgsReferencedRectangle(QgsRectangle(10.6, 43.1, 12, 43.8),
                                   QgsCoordinateReferenceSystem(4326)))
        self.assertEqual(len(spy), 1)
        self.assertEqual(factory.settings.x, [98, 267, 319, 137])
        self.assertEqual(factory.settings.y, [81.87, 74.16, 46.64, 126.73])

        # with reprojection
        factory.set_visible_region(
            QgsReferencedRectangle(
                QgsRectangle(1167379, 5310986, 1367180, 5391728),
                QgsCoordinateReferenceSystem(3857)))
        self.assertEqual(len(spy), 2)
        self.assertEqual(factory.settings.x, [98, 267, 329, 319, 137])
        self.assertEqual(factory.settings.y,
                         [81.87, 74.16, 35.05, 46.64, 126.73])
示例#10
0
    def testMoveBookmark(self):
        """
        Test moving a bookmark from one manager to another
        """
        p = QgsProject()
        manager = QgsBookmarkManager(p)
        manager2 = QgsBookmarkManager(p)

        # add a bunch of bookmarks
        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        manager.addBookmark(b2)
        manager2.addBookmark(b3)

        self.assertEqual(manager.bookmarks(), [b, b2])
        self.assertEqual(manager2.bookmarks(), [b3])

        self.assertFalse(manager.moveBookmark('bbbb', manager2))
        self.assertFalse(manager.moveBookmark(b3.id(), manager2))
        self.assertEqual(manager.bookmarks(), [b, b2])
        self.assertEqual(manager2.bookmarks(), [b3])
        self.assertTrue(manager.moveBookmark(b.id(), manager2))
        self.assertEqual(manager.bookmarks(), [b2])
        self.assertEqual(manager2.bookmarks(), [b3, b])
        self.assertFalse(manager.moveBookmark(b.id(), manager2))
        self.assertTrue(manager2.moveBookmark(b3.id(), manager))
        self.assertEqual(manager.bookmarks(), [b2, b3])
        self.assertEqual(manager2.bookmarks(), [b])
示例#11
0
    def testRemoveBookmark(self):
        project = QgsProject()

        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        self.manager = QgsBookmarkManager.createProjectBasedManager(project)
        bookmark_removed_spy = QSignalSpy(self.manager.bookmarkRemoved)
        bookmark_about_to_be_removed_spy = QSignalSpy(
            self.manager.bookmarkAboutToBeRemoved)
        # tests that bookmark still exists when bookmarkAboutToBeRemoved is fired
        self.manager.bookmarkAboutToBeRemoved.connect(
            self.bookmarkAboutToBeRemoved)

        # not added, should fail
        self.assertFalse(self.manager.removeBookmark(b.id()))
        self.assertEqual(len(bookmark_removed_spy), 0)
        self.assertEqual(len(bookmark_about_to_be_removed_spy), 0)

        self.assertTrue(self.manager.addBookmark(b)[1])
        self.assertEqual(self.manager.bookmarks(), [b])
        self.assertTrue(self.manager.removeBookmark(b.id()))
        self.assertEqual(len(self.manager.bookmarks()), 0)
        self.assertEqual(len(bookmark_removed_spy), 1)
        self.assertEqual(bookmark_removed_spy[0][0], '1')
        self.assertEqual(len(bookmark_about_to_be_removed_spy), 1)
        self.assertEqual(bookmark_about_to_be_removed_spy[0][0], '1')
        self.assertTrue(self.aboutFired)
        self.manager = None
def gcp_bookmark(instance, parameters, context, feedback, inputs):
    """
    Creates a bookmark for the location of each GCP, given the GCP's buffer.
    """
    source = instance.parameterAsSource(parameters, "INPUT", context)
    
    name_field = instance.parameterAsFields(parameters, "NAME_FIELD", context)[0]
    
    bookmark_manager = QgsProject.instance().bookmarkManager()
    coord = source.sourceCrs()
 
    total = 100.0 / source.featureCount() if source.featureCount() else 0
    features = source.getFeatures()
    for current, feature in enumerate(features):
        if feedback.isCanceled():
            break
        
        # Instead of getting the name from an attribute, 
        # this gets the feature's id and turns it into the gcp name.
        gcp_name = str(feature[name_field])
        gcp_view = feature.geometry().boundingBox()
        
        bookmark = QgsBookmark()
        bookmark.setName(gcp_name)
        bookmark.setExtent(QgsReferencedRectangle(gcp_view, coord))

        
        bookmark_manager.addBookmark(bookmark)
        
        feedback.setProgress(int(current * total))
 
    return {"OUTPUT": source.featureCount()}
示例#13
0
    def get(self, request, **kwargs):

        qplotly = QplotlyWidget.objects.get(pk=kwargs['pk'])

        # load settings from db
        settings = QplotlySettings()
        if not settings.read_from_model(qplotly):
            #todo: raise a API exception
            raise Exception()

        # get bbox if is sent
        rect = None
        if 'bbox' in kwargs:
            rect = QgsReferencedRectangle(
                QgsRectangle(**kwargs['bbox']),
                QgsCoordinateReferenceSystem(qplotly.project.group.srid.srid))

        # instace q QplotlyFactory
        factory = QplotlyFactoring(settings, visible_region=rect)

        # is possibile get the first layer
        factory.source_layer = get_qgis_layer(
            qplotly.layers.get(qgs_layer_id=settings.source_layer_id,
                               project_id=kwargs['project_id']))
        factory.rebuild()

        res = {'data': factory.trace}

        self.results.results.update(res)

        return Response(self.results.results)
示例#14
0
def input_to_extent(inp: WPSInput) -> QgsReferencedRectangle:
    """ Convert input to processing extent data
    """
    r = inp[0].data
    rect = QgsRectangle(float(r[0]), float(r[2]), float(r[1]), float(r[3]))
    ref = QgsCoordinateReferenceSystem(inp[0].crs)
    return QgsReferencedRectangle(rect, ref)
示例#15
0
 def testQgsBookmark(self):
     b = QgsBookmark()
     self.assertEqual(b.__repr__(), "<QgsBookmark: '' (0 0, 0 0 - )>")
     b.setName('test bookmark')
     self.assertEqual(b.__repr__(), "<QgsBookmark: 'test bookmark' (0 0, 0 0 - )>")
     b.setExtent(QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4), QgsCoordinateReferenceSystem('EPSG:3111')))
     self.assertEqual(b.__repr__(), "<QgsBookmark: 'test bookmark' (1 2, 3 4 - EPSG:3111)>")
示例#16
0
 def useLayerExtent(self):
     CANVAS_KEY = 'Use canvas extent'
     extentsDict = {}
     extentsDict[CANVAS_KEY] = {
         "extent": iface.mapCanvas().extent(),
         "authid":
         iface.mapCanvas().mapSettings().destinationCrs().authid()
     }
     extents = [CANVAS_KEY]
     layers = QgsProcessingUtils.compatibleLayers(QgsProject.instance())
     for layer in layers:
         authid = layer.crs().authid()
         if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) \
                 and authid is not None:
             layerName = u'{} [{}]'.format(layer.name(), authid)
         else:
             layerName = layer.name()
         extents.append(layerName)
         extentsDict[layerName] = {
             "extent": layer.extent(),
             "authid": authid
         }
     (item, ok) = QInputDialog.getItem(self, self.tr('Select Extent'),
                                       self.tr('Use extent from'), extents,
                                       False)
     if ok:
         self.setValueFromRect(
             QgsReferencedRectangle(
                 extentsDict[item]["extent"],
                 QgsCoordinateReferenceSystem(extentsDict[item]["authid"])))
示例#17
0
    def draw_footprint(self, item):
        self._rubberband.reset(QgsWkbTypes.PolygonGeometry)

        if not item.geometry:
            return

        geom = None

        if item.geometry['type'] == 'Polygon':
            parts = [[QgsPointXY(x, y) for [x, y] in part]
                     for part in item.geometry['coordinates']]
            geom = QgsGeometry.fromPolygonXY(parts)
        elif item.geometry['type'] == 'MultiPolygon':
            parts = [[[QgsPointXY(x, y) for [x, y] in part] for part in multi]
                     for multi in item.geometry['coordinates']]
            geom = QgsGeometry.fromMultiPolygonXY(parts)
        else:
            # unsupported geometry type
            return

        self._rubberband.setToGeometry(geom, crs.crs4326)
        self._rubberband.show()

        bbox = crs.transform(crs.crs4326, crs.get_project_crs(),
                             geom.boundingBox())

        # TODO one day setExtent will support QgsReferencedRectangle :)
        self.canvas.setExtent(
            QgsReferencedRectangle(bbox, crs.get_project_crs()))
        self.canvas.refresh()
示例#18
0
def input_to_extent(inp: WPSInput) -> Any:
    """ Convert to extent 
    """
    r = inp.data
    rect = QgsRectangle(r[0], r[1], r[2], r[3])
    ref = QgsCoordinateReferenceSystem(inp.crs)
    return QgsReferencedRectangle(rect, ref)
示例#19
0
    def testReadWriteXml(self):
        """
        Test reading and writing bookmark manager state to XML
        """
        project = QgsProject()
        manager = QgsBookmarkManager.createProjectBasedManager(project)

        # add a bunch of bookmarks
        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        manager.addBookmark(b2)
        manager.addBookmark(b3)

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

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

        self.assertEqual(len(manager2.bookmarks()), 3)
        names = [c.name() for c in manager2.bookmarks()]
        self.assertCountEqual(names, ['b1', 'b2', 'b3'])
示例#20
0
 def testBookmark(self):
     b = QgsBookmark()
     self.assertFalse(b.id())
     self.assertFalse(b.name())
     b.setId('id')
     self.assertEqual(b.id(), 'id')
     b.setName('name')
     self.assertEqual(b.name(), 'name')
     b.setGroup('group')
     self.assertEqual(b.group(), 'group')
     b.setExtent(
         QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                QgsCoordinateReferenceSystem('EPSG:3111')))
     self.assertEqual(
         b.extent(),
         QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                QgsCoordinateReferenceSystem('EPSG:3111')))
示例#21
0
 def setExtent(self, extent):
     if extent is not None:
         tokens = extent.split(' ')[0].split(',')
         ext = QgsRectangle(float(tokens[0]), float(tokens[2]), float(tokens[1]), float(tokens[3]))
         if len(tokens) > 1:
             self.extent = QgsReferencedRectangle(ext, QgsCoordinateReferenceSystem(tokens[1][1:-1]))
         else:
             self.extent = ext
     self.pixelSizeChanged()
示例#22
0
    def testUpdateBookmark(self):
        project = QgsProject()
        manager = QgsBookmarkManager.createProjectBasedManager(project)
        changed_spy = QSignalSpy(manager.bookmarkChanged)

        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        self.assertFalse(manager.updateBookmark(b))
        self.assertEqual(len(changed_spy), 0)
        manager.addBookmark(b)

        b.setName('new b1')
        self.assertTrue(manager.updateBookmark(b))
        self.assertEqual(manager.bookmarkById('1').name(), 'new b1')
        self.assertEqual(len(changed_spy), 1)
        self.assertEqual(changed_spy[-1][0], '1')

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))
        manager.addBookmark(b2)

        b.setName('new b1 2')
        b2.setName('new b2 2')
        self.assertTrue(manager.updateBookmark(b))
        self.assertEqual(manager.bookmarkById('1').name(), 'new b1 2')
        self.assertEqual(manager.bookmarkById('2').name(), 'b2')
        self.assertEqual(len(changed_spy), 2)
        self.assertEqual(changed_spy[-1][0], '1')
        self.assertTrue(manager.updateBookmark(b2))
        self.assertEqual(manager.bookmarkById('1').name(), 'new b1 2')
        self.assertEqual(manager.bookmarkById('2').name(), 'new b2 2')
        self.assertEqual(len(changed_spy), 3)
        self.assertEqual(changed_spy[-1][0], '2')
示例#23
0
 def getValue(self):
     if str(self.leText.text()).strip() != '':
         try:
             parts = self.leText.text().split(',')
             parts = [float(p) for p in parts]
             r = QgsReferencedRectangle(
                 QgsRectangle(parts[0], parts[2], parts[1], parts[3]),
                 self.crs)
             return r
         except:
             return str(self.leText.text())
     else:
         return None
示例#24
0
    def testClear(self):
        project = QgsProject()
        manager = QgsBookmarkManager.createProjectBasedManager(project)

        # add a bunch of bookmarks
        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        manager.addBookmark(b2)
        manager.addBookmark(b3)

        bookmark_removed_spy = QSignalSpy(manager.bookmarkRemoved)
        bookmark_about_to_be_removed_spy = QSignalSpy(
            manager.bookmarkAboutToBeRemoved)
        manager.clear()
        self.assertEqual(len(manager.bookmarks()), 0)
        self.assertEqual(len(bookmark_removed_spy), 3)
        self.assertEqual(len(bookmark_about_to_be_removed_spy), 3)
示例#25
0
    def testApplicationInstance(self):
        """
        Test storage in the application instance
        """
        manager = QgsApplication.bookmarkManager()

        # add a bunch of bookmarks
        b = QgsBookmark()
        b.setId('1')
        b.setName('b1')
        b.setExtent(
            QgsReferencedRectangle(QgsRectangle(11, 21, 31, 41),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b2 = QgsBookmark()
        b2.setId('2')
        b2.setName('b2')
        b2.setExtent(
            QgsReferencedRectangle(QgsRectangle(12, 22, 32, 42),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        b3 = QgsBookmark()
        b3.setId('3')
        b3.setName('b3')
        b3.setExtent(
            QgsReferencedRectangle(QgsRectangle(32, 32, 33, 43),
                                   QgsCoordinateReferenceSystem('EPSG:4326')))

        manager.addBookmark(b)
        manager.addBookmark(b2)
        manager.addBookmark(b3)

        manager2 = QgsApplication.bookmarkManager()
        self.assertEqual(manager2.bookmarks(), [b, b2, b3])

        manager3 = QgsBookmarkManager(QgsProject.instance())
        self.assertEqual(manager3.bookmarks(), [])
    def triggerResult(self, result):
        self.clear_results()
        if result.userData == FilterNotConfigured:
            self.openConfigWidget()
            self.iface.invalidateLocatorResults()
            return

        # this should be run in the main thread, i.e. mapCanvas should not be None
        geometry = result.userData
        # geometry.transform(self.transform)
        dbg_info(str(geometry.asWkt()))
        dbg_info(geometry.type())

        try:
            rect = QgsReferencedRectangle(geometry.boundingBox(), self.crs)
            rect.scale(4)
            self.map_canvas.setReferencedExtent(rect)
        except AttributeError:
            # QGIS < 3.10 handling
            from qgis.core import QgsCoordinateTransform, QgsProject
            transform = QgsCoordinateTransform(
                self.crs,
                self.map_canvas.mapSettings().destinationCrs(),
                QgsProject.instance())
            geometry.transform(transform)
            rect = geometry.boundingBox()
            rect.scale(4)
            self.map_canvas.setExtent(rect)

        self.map_canvas.refresh()

        if geometry.type() == QgsWkbTypes.PolygonGeometry:
            nflash = 16
            color1: QColor = self.settings.value('polygon_color')
            color2 = color1
            color1.setAlpha(200)
            color2.setAlpha(100)
            self.map_canvas.flashGeometries(
                [geometry], self.crs, color1, color2, nflash,
                self.settings.value('highlight_duration') / nflash * 1000)
        else:
            self.rubberband.reset(geometry.type())
            self.rubberband.addGeometry(geometry, self.crs)

            self.current_timer = QTimer()
            self.current_timer.timeout.connect(self.clear_results)
            self.current_timer.setSingleShot(True)
            self.current_timer.start(
                self.settings.value('highlight_duration') * 1000)
示例#27
0
 def testBookmarkEquality(self):
     b = QgsBookmark()
     b.setId('id')
     b.setName('name')
     b.setGroup('group')
     b.setExtent(
         QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                QgsCoordinateReferenceSystem('EPSG:3111')))
     b2 = QgsBookmark()
     b2.setId('id')
     b2.setName('name')
     b2.setGroup('group')
     b2.setExtent(
         QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                QgsCoordinateReferenceSystem('EPSG:3111')))
     self.assertEqual(b, b2)
     b2.setId('x')
     self.assertNotEqual(b, b2)
     b2.setId('id')
     self.assertEqual(b, b2)
     b2.setName('x')
     self.assertNotEqual(b, b2)
     b2.setName('name')
     self.assertEqual(b, b2)
     b2.setGroup('x')
     self.assertNotEqual(b, b2)
     b2.setGroup('group')
     self.assertEqual(b, b2)
     b2.setExtent(
         QgsReferencedRectangle(QgsRectangle(1, 2, 3, 5),
                                QgsCoordinateReferenceSystem('EPSG:3111')))
     self.assertNotEqual(b, b2)
     b2.setExtent(
         QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                QgsCoordinateReferenceSystem('EPSG:4326')))
     self.assertNotEqual(b, b2)
示例#28
0
    def testPresetFullExtentChangedSignal(self):
        p = QgsProjectViewSettings()
        spy = QSignalSpy(p.presetFullExtentChanged)

        p.setPresetFullExtent(
            QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                   QgsCoordinateReferenceSystem("EPSG:3857")))
        self.assertEqual(len(spy), 1)

        p.setPresetFullExtent(
            QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                   QgsCoordinateReferenceSystem("EPSG:3857")))
        self.assertEqual(len(spy), 1)

        p.setPresetFullExtent(
            QgsReferencedRectangle(QgsRectangle(1, 2, 3, 4),
                                   QgsCoordinateReferenceSystem("EPSG:4326")))
        self.assertEqual(len(spy), 2)

        p.reset()
        self.assertEqual(len(spy), 3)

        p.reset()
        self.assertEqual(len(spy), 3)
示例#29
0
    def value(self):
        """Mimic the QT API to get the value."""
        # Even though it is more work, everytime we should convert the
        # rectangle to string and then parse the string back to a rectangle.
        # This way there is only single source of
        # truth and will keep away a lot of tricky bugs

        value = self.lineEdit.text().strip()

        if not self.is_valid(value):
            return None

        [x1, _, y1, _, x2, _, y2, _, epsg,
         crs_code] = re.findall(self.EXTRACT_REGEX, value)[0]

        p1 = QgsPointXY(float(x1), float(y1))
        p2 = QgsPointXY(float(x2), float(y2))
        rect = QgsReferencedRectangle(
            QgsRectangle(p1, p2), QgsCoordinateReferenceSystem(int(crs_code)))

        return rect
示例#30
0
    def testDefaultViewExtentWithCanvas(self):
        p = QgsProject()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:3857'))

        canvas = QgsMapCanvas()
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        canvas.setFrameStyle(0)
        canvas.resize(600, 400)
        self.assertEqual(canvas.width(), 600)
        self.assertEqual(canvas.height(), 400)
        canvas.setExtent(QgsRectangle(10, 30, 20, 35))
        canvas.show()

        tmpDir = QTemporaryDir()
        tmpFile = "{}/project.qgz".format(tmpDir.path())
        self.assertTrue(p.write(tmpFile))

        QgsProject.instance().read(tmpFile)

        # no default view, extent should not change
        self.assertAlmostEqual(canvas.extent().xMinimum(), 10, 3)
        self.assertAlmostEqual(canvas.extent().yMinimum(), 29.16666, 3)
        self.assertAlmostEqual(canvas.extent().xMaximum(), 20, 3)
        self.assertAlmostEqual(canvas.extent().yMaximum(), 35.833333333, 3)
        self.assertEqual(canvas.mapSettings().destinationCrs().authid(),
                         'EPSG:4326')

        p.viewSettings().setDefaultViewExtent(
            QgsReferencedRectangle(QgsRectangle(1000, 2000, 1500, 2500),
                                   QgsCoordinateReferenceSystem('EPSG:3857')))

        self.assertTrue(p.write(tmpFile))
        QgsProject.instance().read(tmpFile)

        self.assertAlmostEqual(canvas.extent().xMinimum(), 0.0078602, 3)
        self.assertAlmostEqual(canvas.extent().yMinimum(), 0.017966, 3)
        self.assertAlmostEqual(canvas.extent().xMaximum(), 0.01459762, 3)
        self.assertAlmostEqual(canvas.extent().yMaximum(), 0.02245788, 3)
        self.assertEqual(canvas.mapSettings().destinationCrs().authid(),
                         'EPSG:4326')