def loadLayers(theLayerList, theClearFlag=True, theDataDirectory=TESTDATA): """Helper function to load layers as defined in a python list.""" # First unload any layers that may already be loaded if theClearFlag: for myLayer in QgsMapLayerRegistry.instance().mapLayers(): QgsMapLayerRegistry.instance().removeMapLayer(myLayer) # Now go ahead and load our layers myExposureLayerCount = 0 myHazardLayerCount = 0 myCanvasLayers = [] # Now create our new layers for myFile in theLayerList: myLayer, myType = loadLayer(myFile, theDataDirectory) if myType == 'hazard': myHazardLayerCount += 1 elif myType == 'exposure': myExposureLayerCount += 1 # Add layer to the registry (that QGis knows about) QgsMapLayerRegistry.instance().addMapLayer(myLayer) # Create Map Canvas Layer Instance and add to list myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) # Quickly add any existing CANVAS layers to our list first for myLayer in CANVAS.layers(): myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) # now load all these layers in the CANVAS CANVAS.setLayerSet(myCanvasLayers) DOCK.getLayers() # Add MCL's to the CANVAS return myHazardLayerCount, myExposureLayerCount
def addLayers(self, theLayers): """Handle layers being added to the registry so they show up in canvas. .. note: The QgsInterface api does not include this method, it is added here as a helper to facilitate testing. Args: theLayers: list<QgsMapLayer> list of map layers that were added Returns: None Raises: None """ #LOGGER.debug('addLayers called on qgis_interface') #LOGGER.debug('Number of layers being added: %s' % len(theLayers)) #LOGGER.debug('Layer Count Before: %s' % len(self.canvas.layers())) myLayers = self.canvas.layers() myCanvasLayers = [] for myLayer in myLayers: myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) for myLayer in theLayers: myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) self.canvas.setLayerSet(myCanvasLayers)
def addLayer(self, layerId = None): if layerId is None: layer = self.iface.activeLayer() else: layer = QgsMapLayerRegistry.instance().mapLayer(layerId) if layer is None: return prevFlag = self.canvas.renderFlag() self.canvas.setRenderFlag(False) # add the layer to the map canvas layer set self.canvasLayers = [] id2cl_dict = {} for l in self.iface.legendInterface().layers(): lid = self._layerId(l) if self.layerId2canvasLayer.has_key(lid): # previously added cl = self.layerId2canvasLayer[ lid ] elif l == layer: # selected layer cl = QgsMapCanvasLayer(layer) else: continue id2cl_dict[ lid ] = cl self.canvasLayers.append(cl) self.layerId2canvasLayer = id2cl_dict self.canvas.setLayerSet(self.canvasLayers) self.onExtentsChanged() self.canvas.setRenderFlag(prevFlag) self.canvas.repaint() self.canvas.refresh()
def __init__(self, ui): super(RiskTabPresenter, self).__init__(ui) # Load layers shape_files = [ os.path.join(BG_LAYER_PATH, shp_file) for shp_file in BG_LAYER_FILES ] layers = [] for shp_file, color in zip(shape_files, LAYER_COLORS): self.logger.info('Loading {}'.format(shp_file)) path = os.path.abspath(os.path.join(shp_file)) layer = QgsVectorLayer(path, 'shp_file', 'ogr') if not layer.isValid(): self.logger.info('Layer at {} failed to load!'.format(path)) else: symbols = layer.rendererV2().symbols() symbol = symbols[0] symbol.setColor(color) layers.append(layer) QgsMapLayerRegistry.instance().addMapLayer(layer) # Commented out for testing without QGIS initialization #self.loss_layer = RamsisLossPoeLayer('Loss') #layers.append(self.loss_layer) # Set layers canvas_layers = [QgsMapCanvasLayer(l) for l in layers] self.ui.mapWidget.setExtent(QgsRectangle(5.6, 45.6, 10.8, 47.5)) self.ui.mapWidget.setLayerSet(canvas_layers)
def test_defaultTemplate(self): """Test that loading default template works""" LOGGER.info('Testing defaultTemplate') myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myPath = unique_filename(prefix='mapDefaultTemplateTest', suffix='.pdf', dir=temp_dir('test')) myMap.make_pdf(myPath) LOGGER.debug(myPath) myMessage = 'Rendered output does not exist: %s' % myPath assert os.path.exists(myPath), myMessage # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. mySize = os.stat(myPath).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. myExpectedSizes = [ 400350, # Slackware64 14.0 ] myMessage = '%s\nExpected rendered map pdf to be in %s, got %s' % ( myPath, myExpectedSizes, mySize) self.assertIn(mySize, myExpectedSizes, myMessage)
def test_printToPdf(self): """Test making a pdf of the map - this is the most typical use of map. """ LOGGER.info('Testing printToPdf') myLayer, _ = loadLayer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.setImpactLayer(myLayer) myMap.composeMap() myPath = unique_filename(prefix='mapPdfTest', suffix='.pdf', dir=temp_dir('test')) myMap.printToPdf(myPath) LOGGER.debug(myPath) myMessage = 'Rendered output does not exist: %s' % myPath assert os.path.exists(myPath), myMessage # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. mySize = os.stat(myPath).st_size myExpectedSizes = [ 441541, # as rendered on ub 13.04 post 17 May 2013 447217, # Nadia Linux Mint 14 0, # as rendered on Jenkins post 24 April 2013 447138, # Windows 7 SP1 AMD64 ] myMessage = 'Expected rendered map pdf to be in %s, got %s' % ( myExpectedSizes, mySize) self.assertIn(mySize, myExpectedSizes, myMessage)
def __init__(self, *layers): list.__init__(self) self._rawLayers = [] if layers: for l in list(layers): self.insert(0, QgsMapCanvasLayer(l)) self._rawLayers.insert(0, l) QgsMapLayerRegistry.instance().addMapLayer(l)
def update_canvas(self, iface = None): """Update canvas with the new layer + background layers""" layerslist = [QgsMapCanvasLayer(self.layer)] + self.background_layers if iface is not None: iface.mapCanvas().setLayerSet(layerslist) iface.mapCanvas().refresh() else: raise NotImplementedError("This hasn't been developed for standalone")
def commitClicked(self): feature = self.listWidget.currentItem().feature geom = None self.attributesTable.setRowCount(len(feature)) for idx, attrname in enumerate(feature): value = feature[attrname] font = QFont() font.setBold(True) font.setWeight(75) item = QTableWidgetItem(attrname) item.setFont(font) self.attributesTable.setItem(idx, 0, item) self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value))) if geom is None: try: geom = QgsGeometry.fromWkt(value) except: pass self.attributesTable.resizeRowsToContents() self.attributesTable.horizontalHeader().setMinimumSectionSize(150) self.attributesTable.horizontalHeader().setStretchLastSection(True) settings = QSettings() prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') types = ["Point", "LineString", "Polygon"] layers = [] if geom is not None: geomtype = types[int(geom.type())] layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp", "memory") pr = layer.dataProvider() feat = QgsFeature() feat.setGeometry(geom) pr.addFeatures([feat]) layer.updateExtents() layer.selectAll() layer.setExtent(layer.boundingBoxOfSelected()) layer.invertSelection() symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(Qt.green) symbol.setAlpha(0.5) if QGis.QGIS_VERSION_INT < 29900: layer.setRendererV2(QgsSingleSymbolRendererV2(symbol)) else: layer.setRenderer(QgsSingleSymbolRenderer(symbol)) self.mapCanvas.setRenderFlag(False) self.mapCanvas.setLayerSet([QgsMapCanvasLayer(layer)]) QgsMapLayerRegistry.instance().addMapLayer(layer, False) self.mapCanvas.setExtent(layer.extent()) self.mapCanvas.setRenderFlag(True) layers.append(layer) else: self.mapCanvas.setLayerSet([]) settings.setValue('/Projections/defaultBehaviour', prjSetting)
def addLayers(self, layers): """ Handles layers being added to the registry so they show up in canvas. :param layers: A list of map layers (QgsMapLayer) that were added. :type layers: list .. note:: The QgsInterface api does not include this method, it is added here as a helper to facilitate testing. """ current_layers = self.canvas.layers() final_layers = [] for layer in current_layers: final_layers.append(QgsMapCanvasLayer(layer)) for layer in layers: final_layers.append(QgsMapCanvasLayer(layer)) self.canvas.setLayerSet(final_layers)
def addLayers(self, layers): """Handle layers being added to the registry so they show up in canvas. :param layers: list<QgsMapLayer> list of map layers that were added .. note:: The QgsInterface api does not include this method, it is added here as a helper to facilitate testing. """ # LOGGER.debug('addLayers called on qgis_interface') # LOGGER.debug('Number of layers being added: %s' % len(layers)) # LOGGER.debug('Layer Count Before: %s' % len(self.canvas.layers())) current_layers = self.canvas.layers() final_layers = [] for layer in current_layers: final_layers.append(QgsMapCanvasLayer(layer)) for layer in layers: final_layers.append(QgsMapCanvasLayer(layer)) self.canvas.setLayerSet(final_layers)
def refreshLayers(self): """ refresh all layers in canvas """ # add each layer according to order layerSet = [] self.ui.cb_layer_selector.clear() for idx, lyr in enumerate(self.map_layers): if lyr is not None: layerSet.append(QgsMapCanvasLayer(lyr)) self.ui.cb_layer_selector.addItem(self.LAYER_NAMES[idx]) if len(layerSet) > 0: self.canvas.setLayerSet(layerSet)
def showGeoms(self): checks = [self.showRemoteCheck, self.showLocalCheck] layers = [self.oursLayer, self.theirsLayer] toShow = [] for lay, chk in zip(layers, checks): if lay is not None and chk.isChecked(): toShow.append(lay) self.mapCanvas.setRenderFlag(False) self.mapCanvas.setLayerSet( [QgsMapCanvasLayer(layer) for layer in toShow]) self.mapCanvas.setRenderFlag(True)
def _loadTablePreview(self, table, limit=False): """ if has geometry column load to map canvas """ QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setRenderFlag(False) vl = None if table and table.geomType: # limit the query result if required if limit and table.rowCount > 1000: uniqueField = table.getValidQGisUniqueFields(True) if uniqueField is None: self.parent.tabs.setCurrentWidget(self.parent.info) self.parent.infoBar.pushMessage( QApplication.translate( "DBManagerPlugin", "Unable to find a valid unique field"), QgsMessageBar.WARNING, self.parent.iface.messageTimeout()) return uri = table.database().uri() uri.setDataSource( "", u"(SELECT * FROM %s LIMIT 1000)" % table.quotedName(), table.geomColumn, "", uniqueField.name) provider = table.database().dbplugin().providerName() vl = QgsVectorLayer(uri.uri(False), table.name, provider) else: vl = table.toMapLayer() if vl and not vl.isValid(): vl.deleteLater() vl = None # remove old layer (if any) and set new if self.currentLayer: # but not remove it if in layer list panel # fix https://issues.qgis.org/issues/16476 if not QgsProject.instance().layerTreeRoot().findLayer( self.currentLayer.id()): QgsMapLayerRegistry.instance().removeMapLayers( [self.currentLayer.id()]) if vl and vl.isValid(): self.setLayerSet([QgsMapCanvasLayer(vl)]) QgsMapLayerRegistry.instance().addMapLayers([vl], False) self.zoomToFullExtent() else: self.setLayerSet([]) self.currentLayer = vl self.setRenderFlag(True) QApplication.restoreOverrideCursor()
def add_layers(scenario_dir, paths, iface): # pylint: disable=W0621 """Add the layers described in a scenario file to QGIS. :param scenario_dir: Base directory to find path. :type scenario_dir: str :param paths: Path of scenario file (or a list of paths). :type paths: str, list :param iface: iface instance to do necessary things to QGIS. :type iface: QgsInterface :raises: Exception, TypeError, FileNotFoundError Note: * Exception - occurs when paths have illegal extension * TypeError - occurs when paths is not string or list * FileNotFoundError - occurs when file not found """ path_list = [] if isinstance(paths, str): path_list.append(extract_path(scenario_dir, paths)) elif isinstance(paths, list): path_list = [extract_path(scenario_dir, path) for path in paths] else: message = "Paths must be string or list not %s" % type(paths) raise TypeError(message) layer_set = [] for path, base_name in path_list: extension = os.path.splitext(path)[-1] if not os.path.exists(path): raise FileNotFoundError('File not found: %s' % path) if extension in ['.asc', '.tif']: LOGGER.debug("add raster layer %s" % path) # noinspection PyCallingNonCallable layer = QgsRasterLayer(path, base_name) layer_set.append(layer) elif extension in ['.shp']: LOGGER.debug("add vector layer %s" % path) # noinspection PyCallingNonCallable layer = QgsVectorLayer(path, base_name, 'ogr') layer_set.append(layer) else: raise Exception('File %s had illegal extension' % path) # noinspection PyUnresolvedReferences QgsMapLayerRegistry.instance().addMapLayers(layer_set) # noinspection PyCallingNonCallable iface.mapCanvas().setLayerSet( [QgsMapCanvasLayer(layer) for layer in layer_set])
def _load_layers(self): """Manually load all the layers for our project. :return: A list of QgsMapLayer instances. :rtype: list """ layers = [] # First the RW layer host = 'db' port = '5432' user = '******' password = '******' dbname = 'gis' uri = QgsDataSourceURI() uri.setConnection(host, port, dbname, user, password) schema = 'public' table = 'flood_mapper_rw' geometry_column = 'geometry' where_clause = '' title = 'RW' uri.setDataSource(schema, table, geometry_column, where_clause) layer = QgsVectorLayer(uri.uri(), title, 'postgres') QgsMapLayerRegistry.instance().addMapLayer(layer, False) canvas_layer = QgsMapCanvasLayer(layer) layers.append(canvas_layer) # Now the JK layer path = './data/jk.shp' title = 'JK' layer = QgsVectorLayer(path, title, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(layer, False) canvas_layer = QgsMapCanvasLayer(layer) layers.append(canvas_layer) return layers
def test_custom_logo(self): """Test that setting user-defined logo works.""" LOGGER.info('Testing custom_logo') layer, _ = load_layer('test_shakeimpact.shp') canvas_layer = QgsMapCanvasLayer(layer) CANVAS.setLayerSet([canvas_layer]) rect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(rect) CANVAS.refresh() report = Map(IFACE) report.set_impact_layer(layer) report.set_organisation_logo(":/plugins/inasafe/logo-flower.png") out_path = unique_filename(prefix='mapCustomLogoTest', suffix='.pdf', dir=temp_dir('test')) report.make_pdf(out_path) LOGGER.debug(out_path) message = 'Rendered output does not exist: %s' % out_path self.assertTrue(os.path.exists(out_path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. out_size = os.stat(out_path).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. expected_sizes = [ 402083, # Ubuntu 13.04_64 400563, # Ubuntu 13.10_64 450385, # Ubuntu 14.04_64 AG 413193, # Ubuntu 14.04_64 TS pycharm 416313, # Ubuntu 14.04_64 TS make - TODO why is this? 419483, # Ubuntu 14.04_64 MB pycharm 413193, # Ubuntu 14.04_64 MB make - TODO why is this? 418847, # Ubuntu 14.04_64 IS pycharm 412764, # Ubuntu 14.04_64 IS make - TODO why is this? 367934, # Slackware64 14.0 82263, # Linux Mint 14_64 85418, # Windows 7 32bit 88779, # Windows 7 64bit 436118, # Jenkins ub 12.04 433856, # Travis ] message = '%s\nExpected rendered map pdf to be in %s, got %s' % ( out_path, expected_sizes, out_size) self.assertIn(out_size, expected_sizes, message)
def test_default_template(self): """Test that loading default template works""" LOGGER.info('Testing default_template') layer, _ = load_layer('test_shakeimpact.shp') canvas_layer = QgsMapCanvasLayer(layer) CANVAS.setLayerSet([canvas_layer]) rect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(rect) CANVAS.refresh() report = Map(IFACE) report.set_impact_layer(layer) out_path = unique_filename(prefix='mapDefaultTemplateTest', suffix='.pdf', dir=temp_dir('test')) report.make_pdf(out_path) LOGGER.debug(out_path) message = 'Rendered output does not exist: %s' % out_path self.assertTrue(os.path.exists(out_path), message) # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. out_size = os.stat(out_path).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. expected_sizes = [ 405359, # Ubuntu 13.04_64 427172, # Ubuntu 13.10_64 468836, # Ubuntu 14.04_64 AG 431844, # Ubuntu 14.04_64 TS - pycharm 431873, # Ubuntu 14.04_64 TS - make - TODO why is this? 437994, # Ubuntu 14.04_64 MB - pycharm 431844, # Ubuntu 14.04_64 MB - make - TODO why is this? 434420, # Ubuntu 14.04_64 IS - pycharm 428339, # Ubuntu 14.04_64 IS - make - TODO why is this? 414589, # Slackware64 14.0 144542, # Linux Mint 14_64 148267, # Windows 7 32 150412, # Windows 7 64 448270, # UB 12.04 Jenkins 449448, # Travis ] message = '%s\nExpected rendered map pdf to be in %s, got %s' % ( out_path, expected_sizes, out_size) self.assertIn(out_size, expected_sizes, message)
def loadLayers(): """ Helper function to load layers into the dialog. """ # First unload any layers that may already be loaded for myLayer in QgsMapLayerRegistry.instance().mapLayers(): QgsMapLayerRegistry.instance().removeMapLayer(myLayer) # Now go ahead and load our layers myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) myData = os.path.join(myRoot, 'test_data') myData = myData.replace('Tim Sutton', 'TIMSUT~1') myData = myData.replace('Rudi Thiede', 'RUDI~1') # List all layers in the correct order. myFileList = ['test.shp'] myCanvasLayers = [] for myFile in myFileList: # Extract basename and absolute path myBaseName, myExt = os.path.splitext(myFile) myPath = os.path.join(myData, myFile) # Create QGis Layer Instance if myExt in ['.asc', '.tif']: myLayer = QgsRasterLayer(myPath, myBaseName) elif myExt in ['.shp']: myLayer = QgsVectorLayer(myPath, myBaseName, 'ogr') else: msg = 'File %s had illegal extension' % myPath raise Exception(msg) msg = 'Layer "%s" is not valid' % str(myLayer.source()) assert myLayer.isValid(), msg # Add layer to the registry (that QGis knows about) QgsMapLayerRegistry.instance().addMapLayer(myLayer) # Create Map Canvas Layer Instance and add to list myCanvasLayers.append(QgsMapCanvasLayer(myLayer)) # Add MCL's to the CANVAS # NOTE: New layers *must* be added to the end of this list, otherwise # tests will break. CANVAS.setLayerSet(myCanvasLayers)
def test_renderComposition(self): """Test making an image of the map only.""" LOGGER.info('Testing renderComposition') myLayer, _ = loadLayer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.setImpactLayer(myLayer) myMap.composeMap() myImagePath, myControlImage, myTargetArea = myMap.renderComposition() LOGGER.debug(myImagePath) assert myControlImage is not None myDimensions = [ myTargetArea.left(), myTargetArea.top(), myTargetArea.bottom(), myTargetArea.right() ] myExpectedDimensions = [0.0, 0.0, 3507.0, 2480.0] myMessage = 'Expected target area to be %s, got %s' % ( str(myExpectedDimensions), str(myDimensions)) assert myExpectedDimensions == myDimensions, myMessage myMessage = 'Rendered output does not exist' assert os.path.exists(myImagePath), myMessage myAcceptableImages = [ 'renderComposition.png', 'renderComposition-variantUB12.04.png', 'renderComposition-variantWindosVistaSP2-32.png', 'renderComposition-variantJenkins.png', 'renderComposition-variantUB11.10-64.png', 'renderComposition-variantUB11.04-64.png' ] # Beta version and version changes can introduce a few extra chars # into the metadata section so we set a reasonable tolerance to cope # with this. myTolerance = 8000 myFlag, myMessage = checkImages(myAcceptableImages, myImagePath, myTolerance) assert myFlag, myMessage
def Xtest_renderTemplate(self): """Test that load template works""" #Use the template from our resources bundle myInPath = ':/plugins/inasafe/basic.qpt' myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myMap = Map(IFACE) set_jakarta_extent() myMap.set_impact_layer(myLayer) myPath = unique_filename(prefix='outTemplate', suffix='.pdf', dir=temp_dir('test')) LOGGER.debug(myPath) myMap.render_template(myInPath, myPath) assert os.path.exists(myPath)
def test_renderTemplate(self): """Test that load template works""" #Use the template from our resources bundle myInPath = ':/plugins/inasafe/basic.qpt' myLayer, myType = loadLayer('test_shakeimpact.shp') del myType myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myMap = Map(IFACE) setJakartaGeoExtent() myMap.setImpactLayer(myLayer) myOutPath = os.path.join(temp_dir(), 'outTemplate.pdf') if os.path.exists(myOutPath): os.remove(myOutPath) myMap.renderTemplate(myInPath, myOutPath) assert os.path.exists(myOutPath)
def test_inasafeMap(self): """Test making a pdf using the Map class.""" myLayer, myType = loadLayer('test_shakeimpact.shp') del myType myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myMap = Map(IFACE) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap.setImpactLayer(myLayer) myPath = os.path.join(temp_dir(), 'outCustom.pdf') if os.path.exists(myPath): os.remove(myPath) myMap.makePdf(myPath) assert os.path.exists(myPath) # ,, note:: Template writing is experimental myMap.writeTemplate(os.path.join(temp_dir(), 'template.qpt'))
def addLayer(self, layer): """Handle a layer being added to the registry so it shows up in canvas. :param layer: list<QgsMapLayer> list of map layers that were added .. note: The QgsInterface api does not include this method, it is added here as a helper to facilitate testing. .. note: The addLayer method was deprecated in QGIS 1.8 so you should not need this method much. """ # set the recently added layer as active # LOGGER.debug('Layer Count Before: %s' % len(self.canvas.layers())) current_layers = self.canvas.layers() final_layers = [] + current_layers final_layers.append(QgsMapCanvasLayer(layer)) self.canvas.setLayerSet(final_layers) self.active_layer = layer
def updatePreview(self): if self.mapSettings is None: return if not self.canvasReady: c = self.ui.canvas s = self.mapSettings c.setCanvasColor(s.backgroundColor()) c.setCrsTransformEnabled(s.hasCrsTransformEnabled()) c.setDestinationCrs(s.destinationCrs()) if QGis.QGIS_VERSION_INT >= 20700: c.setRotation(s.rotation()) c.setExtent(s.extent()) self.canvasReady = True self.ui.canvas.setLayerSet([QgsMapCanvasLayer(layer) for layer in self.visibleLayers()])
def test_printToPdf(self): """Test making a pdf of the map - this is the most typical use of map. """ LOGGER.info('Testing printToPdf') myLayer, _ = load_layer('test_shakeimpact.shp') myCanvasLayer = QgsMapCanvasLayer(myLayer) CANVAS.setLayerSet([myCanvasLayer]) myRect = QgsRectangle(106.7894, -6.2308, 106.8004, -6.2264) CANVAS.setExtent(myRect) CANVAS.refresh() myMap = Map(IFACE) myMap.set_impact_layer(myLayer) myMap.compose_map() myPath = unique_filename(prefix='mapPdfTest', suffix='.pdf', dir=temp_dir('test')) myMap.make_pdf(myPath) LOGGER.debug(myPath) myMessage = 'Rendered output does not exist: %s' % myPath assert os.path.exists(myPath), myMessage # pdf rendering is non deterministic so we can't do a hash check # test_renderComposition renders just the image instead of pdf # so we hash check there and here we just do a basic minimum file # size check. mySize = os.stat(myPath).st_size # Note: You should replace, not append the numbers for a given # platform. Also note that this test will break every time the # version number of InaSAFE changes so we should ultimately come up # with a lower maintenance test strategy. myExpectedSizes = [ 441541, # as rendered on ub 13.04 post 17 May 2013 441563, # as rendered on ub 13.04 18 Jul 2013 447217, # Nadia Linux Mint 14 447144, # as rendered on Jenkins post 29 July 2013 447172, # Windows 7 SP1 AMD64 446839, # Windows 8 AMD64 post 27 Aug 2013 234138, # OSX 10.8 444421, # Slackware64 14.0 ] myMessage = '%s\nExpected rendered map pdf to be in %s, got %s' % ( myPath, myExpectedSizes, mySize) self.assertIn(mySize, myExpectedSizes, myMessage)
def _loadTablePreview(self, table, limit=False): """ if has geometry column load to map canvas """ QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setRenderFlag(False) newLayerId = None if table.geomType: # limit the query result if required if limit and table.rowCount > 1000: uniqueField = table.getValidQGisUniqueFields(True) if uniqueField == None: QMessageBox.warning( self, QApplication.translate("DBManagerPlugin", "Sorry"), QApplication.translate( "DBManagerPlugin", "Unable to find a valid unique field")) return uri = table.database().uri() uri.setDataSource( "", u"(SELECT * FROM %s LIMIT 1000)" % table.quotedName(), table.geomColumn, "", uniqueField.name) provider = table.database().dbplugin().providerName() vl = QgsVectorLayer(uri.uri(), table.name, provider) else: vl = table.toMapLayer() if not vl.isValid(): self.setLayerSet([]) else: newLayerId = vl.id() if hasattr(vl, 'id') else vl.id() self.setLayerSet([QgsMapCanvasLayer(vl)]) QgsMapLayerRegistry.instance().addMapLayers([vl], False) self.zoomToFullExtent() # remove old layer (if any) and set new if self.currentLayerId: QgsMapLayerRegistry.instance().removeMapLayers( [self.currentLayerId], False) self.currentLayerId = newLayerId self.setRenderFlag(True) QApplication.restoreOverrideCursor()
def _setUp(self): """Runs before each test.""" # create a map canvas widget CANVAS.setCanvasColor(QtGui.QColor('white')) CANVAS.enableAntiAliasing(True) # load a shapefile self.beforePath = os.path.join('data', 'before.tif') beforeLayer = QgsRasterLayer(self.beforePath, 'before', 'ogr') # add the layer to the canvas and zoom to it QgsMapLayerRegistry.instance().addMapLayer(beforeLayer) CANVAS.setLayerSet([QgsMapCanvasLayer(beforeLayer)]) CANVAS.setExtent(beforeLayer.extent()) # import the plugin to be tested import massive_change_detection self.plugin = massive_change_detection.classFactory(IFACE) self.plugin.initGui() self.dlg = self.plugin.dlg
def addLayer(self): layerPath = QFileDialog.getOpenFileName(self, u'Abrir shapefile', '.', 'Shapefiles (*.shp)') layerInfo = QFileInfo(layerPath) layerProvider = 'ogr' # name = '/home/cbdavide/Documentos/Projects/shape-viewer/Colombia/Colombia.shp' # layer = QgsVectorLayer(name, 'ejje', layerProvider) layer = QgsVectorLayer(layerPath, layerInfo.fileName(), layerProvider) if not layer.isValid(): return # Cambiar el color del layer symbol_layer = layer.rendererV2().symbols()[0].symbolLayer(0) symbol_layer.setColor(QColor(176, 251, 163)) QgsMapLayerRegistry.instance().addMapLayer(layer) if self.canvas.layerCount() == 0: self.canvas.setExtent(layer.extent()) self.layers.insert(0, QgsMapCanvasLayer(layer)) self.canvas.setLayerSet(self.layers)
def test_analysis_wizard(self): """Test Analysis Wizard.""" dialog = WizardDialog(iface=IFACE) dialog.dock = self.dock dialog.set_function_centric_mode() QgsMapLayerRegistry.instance().removeAllMapLayers() number_of_column = len(hazard_all) volcano_layer = load_test_vector_layer('hazard', 'volcano_krb.shp', clone=True) structure_layer = load_test_vector_layer('exposure', 'buildings.shp', clone=True) test_layers = [volcano_layer, structure_layer] QgsMapLayerRegistry.instance().addMapLayers(test_layers) # Need to set the layers manually to map canvas. See: # https://gist.github.com/ismailsunni/dd2c30a38cef0147bd0dc8d6ba1aeac6 qgs_map_canvas_layers = [QgsMapCanvasLayer(x) for x in test_layers] CANVAS.setLayerSet(qgs_map_canvas_layers) count = len(dialog.iface.mapCanvas().layers()) self.assertEqual(count, len(test_layers)) # step_fc_functions1: test function matrix dimensions col_count = dialog.step_fc_functions1.tblFunctions1.columnCount() self.assertEqual(col_count, number_of_column) row_count = dialog.step_fc_functions1.tblFunctions1.rowCount() self.assertEqual(row_count, len(exposure_all)) # Select Volcano vs Structure volcano_index = hazard_all.index(hazard_volcano) structure_index = exposure_all.index(exposure_structure) dialog.step_fc_functions1.tblFunctions1.setCurrentCell( structure_index, volcano_index) selected_hazard = dialog.step_fc_functions1.selected_value( layer_purpose_hazard['key']) selected_exposure = dialog.step_fc_functions1.selected_value( layer_purpose_exposure['key']) self.assertEqual(selected_hazard, hazard_volcano) self.assertEqual(selected_exposure, exposure_structure) # step_fc_functions1: press next dialog.pbnNext.click() # step_fc_functions2 # Check in the correct step self.check_current_step(dialog.step_fc_functions2) hazard_polygon_index = get_allowed_geometries( layer_purpose_hazard['key']).index(layer_geometry_polygon) exposure_polygon_index = get_allowed_geometries( layer_purpose_exposure['key']).index(layer_geometry_polygon) dialog.step_fc_functions2.tblFunctions2.setCurrentCell( exposure_polygon_index, hazard_polygon_index) selected_hazard_geometry = dialog.step_fc_functions2.selected_value( layer_purpose_hazard['key']) selected_exposure_geometry = dialog.step_fc_functions2.selected_value( layer_purpose_exposure['key']) self.assertEqual(selected_hazard_geometry, layer_geometry_polygon) self.assertEqual(selected_exposure_geometry, layer_geometry_polygon) # step_fc_functions2: press next dialog.pbnNext.click() # Check in the correct step self.check_current_step(dialog.step_fc_hazlayer_origin) # step hazard origin: press next dialog.pbnNext.click() # Check in the correct step self.check_current_step(dialog.step_fc_hazlayer_from_canvas) # Check the number of layer in the list self.assertEqual( dialog.step_fc_hazlayer_from_canvas.lstCanvasHazLayers.count(), 1) # step hazard from canvas: press next dialog.pbnNext.click() # Check in the correct step self.check_current_step(dialog.step_fc_explayer_origin) # step exposure origin: press next dialog.pbnNext.click() # Check in the correct step self.check_current_step(dialog.step_fc_explayer_from_canvas) # Check the number of layer in the list self.assertEqual( dialog.step_fc_explayer_from_canvas.lstCanvasExpLayers.count(), 1) # step exposure from canvas: press next dialog.pbnNext.click() # Check in the correct step self.check_current_step(dialog.step_fc_agglayer_origin) # Check no aggregation dialog.step_fc_agglayer_origin.rbAggLayerNoAggregation.setChecked(True) # step aggregation origin: press next dialog.pbnNext.click() # Check in the correct step self.check_current_step(dialog.step_fc_summary) # step extent: press next dialog.pbnNext.click() # Check in the correct step self.check_current_step(dialog.step_fc_analysis)