def testSymbol(self): """ Test setting a page symbol for the collection """ p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() self.assertTrue(collection.pageStyleSymbol()) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeColor(Qt.red) fill.setStrokeWidth(6) collection.setPageStyleSymbol(fill_symbol) self.assertEqual(collection.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00') self.assertEqual(collection.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
def testReadWriteXml(self): p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeColor(Qt.red) fill.setStrokeWidth(6) collection.setPageStyleSymbol(fill_symbol) # add a page page = QgsLayoutItemPage(l) page.setPageSize('A4') self.assertEqual(collection.pageNumber(page), -1) collection.addPage(page) # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') collection.addPage(page2) doc = QDomDocument("testdoc") elem = doc.createElement("test") self.assertTrue(collection.writeXml(elem, doc, QgsReadWriteContext())) l2 = QgsLayout(p) collection2 = l2.pageCollection() self.assertTrue(collection2.readXml(elem.firstChildElement(), doc, QgsReadWriteContext())) self.assertEqual(collection2.pageCount(), 2) self.assertEqual(collection2.page(0).pageSize().width(), 210) self.assertEqual(collection2.page(0).pageSize().height(), 297) self.assertEqual(collection2.page(1).pageSize().width(), 148) self.assertEqual(collection2.page(1).pageSize().height(), 210) self.assertEqual(collection2.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00') self.assertEqual(collection2.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
def testReadWriteXml(self): p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeColor(Qt.red) fill.setStrokeWidth(6) collection.setPageStyleSymbol(fill_symbol) # add a page page = QgsLayoutItemPage(l) page.setPageSize('A4') self.assertEqual(collection.pageNumber(page), -1) collection.addPage(page) # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') collection.addPage(page2) doc = QDomDocument("testdoc") elem = doc.createElement("test") self.assertTrue(collection.writeXml(elem, doc, QgsReadWriteContext())) l2 = QgsLayout(p) collection2 = l2.pageCollection() self.assertTrue(collection2.readXml(elem.firstChildElement(), doc, QgsReadWriteContext())) self.assertEqual(collection2.pageCount(), 2) self.assertEqual(collection2.page(0).pageSize().width(), 210) self.assertEqual(collection2.page(0).pageSize().height(), 297) self.assertEqual(collection2.page(1).pageSize().width(), 148) self.assertEqual(collection2.page(1).pageSize().height(), 210) self.assertEqual(collection2.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00') self.assertEqual(collection2.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
def testSymbol(self): """ Test setting a page symbol for the collection """ p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() self.assertTrue(collection.pageStyleSymbol()) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeColor(Qt.red) fill.setStrokeWidth(6) collection.setPageStyleSymbol(fill_symbol) self.assertEqual( collection.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00') self.assertEqual( collection.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
def append_SimpleFillSymbolLayer(symbol, layer: SimpleFillSymbolLayer): """ Appends a SimpleFillSymbolLayer to a symbol """ fill_color = symbol_color_to_qcolor(layer.color) out = QgsSimpleFillSymbolLayer(fill_color) out.setEnabled(layer.enabled) out.setLocked(layer.locked) if isinstance(layer, SimpleFillSymbolLayer): if layer.outline_layer: if isinstance(layer.outline_layer, (SimpleLineSymbolLayer, CartographicLineSymbolLayer)): out.setStrokeColor(symbol_color_to_qcolor(layer.outline_layer.color)) out.setStrokeWidth(layer.outline_layer.width) out.setStrokeWidthUnit(QgsUnitTypes.RenderPoints) if isinstance(layer.outline_layer, SimpleLineSymbolLayer): out.setStrokeStyle(symbol_pen_to_qpenstyle(layer.outline_layer.line_type)) if isinstance(layer.outline_layer, CartographicLineSymbolLayer): out.setPenJoinStyle(symbol_pen_to_qpenjoinstyle(layer.outline_layer.join)) # better matching of null stroke color to QGIS symbology if out.strokeColor().alpha() == 0: out.setStrokeStyle(Qt.NoPen) # todo - change to new symbol layer if outline offset, template, etc set symbol.appendSymbolLayer(out) elif layer.outline_symbol: # outline is a symbol itself out.setStrokeStyle(Qt.NoPen) symbol.appendSymbolLayer(out) # get all layers from outline append_SymbolLayer_to_QgsSymbolLayer(symbol, layer.outline_symbol) else: out.setStrokeStyle(Qt.NoPen) symbol.appendSymbolLayer(out) elif isinstance(layer, ColorSymbol): out.setStrokeStyle(Qt.NoPen) symbol.appendSymbolLayer(out)
def btnLaunchAction(self): """btnLaunch action""" # Paramètres du web service IGN de calcul d'isochrone x = 2.424626 y = 48.845793 location = '{},{}'.format(x, y) method = 'time' # time distance graphname = 'Voiture' # Voiture Pieton time = 90 * 60 # si method time distance = 100000 # si method distance holes = False # True False smoothing = True # True False epsg = 4326 apiKey = 'choisirgeoportail' # Paramètres de symbologie fillRed = QColor(251, 154, 153) fillBlue = QColor(166, 206, 227) fillGreen = QColor(178, 223, 138) fillColor = fillGreen strokeRed = QColor(251, 154, 153) strokeBlue = QColor(31, 120, 180) strokeGreen = QColor(51, 160, 44) strokeColor = strokeGreen borderWidth = 0.4 opacity = 0.7 # url du service de calcul if method == 'time': param = 'time={}'.format(time) elif method == 'distance': param = 'distance={}'.format(distance) url = ''' https://wxs.ign.fr/{}/isochrone/isochrone.xml?location={}&method={}&graphName={}&exclusions=&{}&holes={}&smoothing={} '''.format(apiKey, location, method, graphname, param, holes, smoothing) print(url) # Récupération du User-Agent QGIS s = QgsSettings() userAgent = s.value('/qgis/networkAndProxy/userAgent', 'Mozilla/5.0') headers = {'User-Agent': userAgent} # Appel du service #xmlResponse = requests.get(url, timeout=10) xmlResponse = requests.get(url, headers=headers) print(xmlResponse) # Décodage de la réponse et récupération de la géométrie root = ElementTree.fromstring(xmlResponse.content) wktGeometry = root.find('wktGeometry') #print(wktGeometry.text) if wktGeometry is not None: # Construction de la requête sql sql = ''' select st_geomfromtext('{}', {}) geom '''.format(wktGeometry.text, epsg) #print(sql) # Construction de la couche virtuelle if method == 'time': libLayer = '{}_{}_minutes'.format(graphname, int(time / 60)) elif method == 'distance': libLayer = '{}_{}_kilometres'.format(graphname, int(distance / 1000)) vLayer = QgsVectorLayer('?query={}'.format(sql), libLayer, 'virtual') #symbol = QgsFillSymbol() #symbol.setColor(fillColor) symbolLayer = QgsSimpleFillSymbolLayer() symbolLayer.setStrokeWidth(borderWidth) symbolLayer.setStrokeColor(strokeColor) symbolLayer.setFillColor(fillColor) vLayer.renderer().symbols(QgsRenderContext())[0].changeSymbolLayer( 0, symbolLayer) vLayer.setOpacity(opacity) # Pour essai QgsProject.instance().addMapLayer(vLayer) else: print('Échec de l\'appel du service')
def styleCreator(self, layer, index, id_attr, id_value, spacing, crossX, crossY, scale, color, fontSize, font, fontLL, llcolor, utmcheck): """Getting Input Data For Grid Generation""" grid_spacing = spacing geo_number_x = crossX geo_number_y = crossY fSize = fontSize fontType = font LLfontType = fontLL #Loading feature layer_bound = layer query = '"' + str(id_attr) + '"=' + str(id_value) layer_bound.selectByExpression(query, QgsVectorLayer.SelectBehavior(0)) feature_bound = layer_bound.selectedFeatures()[0] layer_bound.removeSelection() #Getting Feature Source CRS and Geometry if utmcheck: feature_geometry = feature_bound.geometry() bound_UTM = layer_bound.crs().authid() feature_bbox = feature_geometry.boundingBox() bound_UTM_bb = str(feature_bbox).replace(',', '').replace('>', '') # Transforming to Geographic transform_feature = QgsCoordinateTransform( QgsCoordinateReferenceSystem(bound_UTM), QgsCoordinateReferenceSystem('EPSG:4674'), QgsProject.instance()) feature_geometry.transform(transform_feature) bound_sourcecrs = 'EPSG:4674' feature_bbox = feature_geometry.boundingBox() feature_bbox_or = feature_geometry.orientedMinimumBoundingBox() else: feature_geometry = feature_bound.geometry() bound_sourcecrs = layer_bound.crs().authid() feature_bbox = feature_geometry.boundingBox() feature_bbox_or = feature_geometry.orientedMinimumBoundingBox() geo_bound_bb = str(feature_bbox).replace(',', '').replace('>', '') oriented_geo_bb = str(feature_bbox_or).replace(',', '').replace( '>', '').replace('((', '').replace('))', '') #Defining CRSs Transformations inom = feature_bound[index] if inom[0] == 'N': bound_UTM = 'EPSG:319' + str(72 + int(inom[3:5]) - 18) elif inom[0] == 'S': bound_UTM = 'EPSG:319' + str(78 + int(inom[3:5]) - 18) else: iface.messageBar().pushMessage("Error", "Invalid index attribute", level=Qgis.Critical) return trLLUTM = QgsCoordinateTransform( QgsCoordinateReferenceSystem(bound_sourcecrs), QgsCoordinateReferenceSystem(bound_UTM), QgsProject.instance()) trUTMLL = QgsCoordinateTransform( QgsCoordinateReferenceSystem(bound_UTM), QgsCoordinateReferenceSystem(bound_sourcecrs), QgsProject.instance()) #Defining UTM Grid Symbology Type renderer = layer.renderer() properties = {'color': 'black'} grid_symb = QgsFillSymbol.createSimple(properties) symb_out = QgsSimpleFillSymbolLayer() symb_out.setStrokeColor(QColor('black')) symb_out.setFillColor(QColor('white')) symb_out.setStrokeWidth(0.05) """ Creating UTM Grid """ if not utmcheck: geo_UTM = feature_bound.geometry() geo_UTM.transform(trLLUTM) bound_UTM_bb = str(geo_UTM.boundingBox()).replace(',', '').replace( '>', '') xmin_UTM = float(bound_UTM_bb.split()[1]) ymin_UTM = float(bound_UTM_bb.split()[2]) xmax_UTM = float(bound_UTM_bb.split()[3]) ymax_UTM = float(bound_UTM_bb.split()[4]) if grid_spacing > 0: UTM_num_x = floor(xmax_UTM / grid_spacing) - floor( xmin_UTM / grid_spacing) UTM_num_y = floor(ymax_UTM / grid_spacing) - floor( ymin_UTM / grid_spacing) #Generating Vertical Lines for x in range(1, UTM_num_x + 1): grid_symb = self.utm_symb_generator( grid_spacing, trUTMLL, trLLUTM, grid_symb, properties, geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, x, 0, geo_bound_bb, bound_UTM_bb, utmcheck) #Generating Horizontal Lines for y in range(1, UTM_num_y + 1): grid_symb = self.utm_symb_generator( grid_spacing, trUTMLL, trLLUTM, grid_symb, properties, geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, 0, y, geo_bound_bb, bound_UTM_bb, utmcheck) """ Creating Geo Grid """ grid_symb = self.geoGridcreator(grid_symb, geo_bound_bb, geo_number_x, geo_number_y, scale, utmcheck, trLLUTM) """ Rendering UTM and Geographic Grid """ #Changing UTM Grid Color grid_symb.setColor(color) grid_symb.changeSymbolLayer(0, symb_out) #Creating Rule Based Renderer (Rule For The Other Features) properties = {'color': 'white'} ext_grid_symb = QgsFillSymbol.createSimple(properties) symb_ot = QgsRuleBasedRenderer.Rule(ext_grid_symb) symb_ot.setFilterExpression('\"' + str(id_attr) + '\" <> ' + str(id_value)) symb_ot.setLabel('other') #Creating Rule Based Renderer (Rule For The Selected Feature, Root Rule) symb_new = QgsRuleBasedRenderer.Rule(grid_symb) symb_new.setFilterExpression('\"' + str(id_attr) + '\" = ' + str(id_value)) symb_new.setLabel('layer') symb_new.appendChild(symb_ot) #Applying New Renderer render_base = QgsRuleBasedRenderer(symb_new) new_renderer = QgsInvertedPolygonRenderer.convertFromRenderer( render_base) layer_bound.setRenderer(new_renderer) """ Labeling Geo Grid """ if utmcheck: dx = [ 2 * scale * fSize / 1.5, -13.6 * scale * fSize / 1.5, 6 * scale * fSize / 1.5 ] dy = [1.7 * scale * fSize / 1.5, -3.8 * scale * fSize / 1.5] else: dx = [0.000018 * scale, -0.000120 * scale, 0.00005 * scale] dy = [0.000015 * scale, -0.000040 * scale] root_rule = self.geoGridlabelPlacer(geo_bound_bb, geo_number_x, geo_number_y, dx, dy, fSize, LLfontType, trLLUTM, trUTMLL, llcolor, utmcheck, scale) """ Labeling UTM Grid""" if utmcheck: dx = [-2.7, -9.7, -6.2, 5.4] dx = [i * scale * fSize / 1.5 for i in dx] dy = [2.5, -1.7, -0.5, -1.5] dy = [i * scale * fSize / 1.5 for i in dy] dy0 = [5.45, -4.8, -3.2, -4.2] dy0 = [i * scale * fSize / 1.5 for i in dy0] dy1 = [2.15, 1.2] dy1 = [i * scale * fSize / 1.5 for i in dy1] else: dx = [-0.00003, -0.000107, -0.000070, 0.000060] dx = [i * scale * fSize / 1.5 for i in dx] dy = [0.000027, 0.000016, -0.000041, -0.000052] dy = [i * scale * fSize / 1.5 for i in dy] dy0 = [0.0000644, 0.000053, -0.000076, -0.000087] dy0 = [i * scale * fSize / 1.5 for i in dy0] dy1 = [0.000032, 0.000020] dy1 = [i * scale * fSize / 1.5 for i in dy1] root_rule = self.utmGridlabelPlacer( root_rule, grid_spacing, geo_bound_bb, bound_UTM_bb, geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, trUTMLL, trLLUTM, dx, dy, dy0, dy1, fSize, fontType, scale, utmcheck, oriented_geo_bb) """ Activating Labels """ rules = QgsRuleBasedLabeling(root_rule) layer.setLabeling(rules) layer.setLabelsEnabled(True) layer.triggerRepaint() return
def append_SimpleFillSymbolLayer( symbol, # pylint: disable=too-many-branches layer: SimpleFillSymbolLayer, context: Context): """ Appends a SimpleFillSymbolLayer to a symbol """ fill_color = symbol_color_to_qcolor(layer.color) out = QgsSimpleFillSymbolLayer(fill_color) out.setEnabled(layer.enabled) out.setLocked(layer.locked) if isinstance(layer, SimpleFillSymbolLayer): if layer.outline_layer: if isinstance( layer.outline_layer, (SimpleLineSymbolLayer, CartographicLineSymbolLayer)): out.setStrokeColor( symbol_color_to_qcolor(layer.outline_layer.color)) out.setStrokeWidth( context.convert_size(layer.outline_layer.width)) out.setStrokeWidthUnit(context.units) if isinstance(layer.outline_layer, SimpleLineSymbolLayer): out.setStrokeStyle( symbol_pen_to_qpenstyle(layer.outline_layer.line_type)) if isinstance(layer.outline_layer, CartographicLineSymbolLayer): out.setPenJoinStyle( symbol_pen_to_qpenjoinstyle(layer.outline_layer.join)) # better matching of null stroke color to QGIS symbology if out.strokeColor().alpha() == 0: out.setStrokeStyle(Qt.NoPen) # TODO try: if layer.outline_layer.offset: raise NotImplementedException( 'Fill outline offset not supported') except AttributeError: pass try: if layer.outline_layer.template: raise NotImplementedException( 'Fill outline template not supported') except AttributeError: pass try: if layer.outline_layer.decoration: raise NotImplementedException( 'Fill outline decoration not supported') except AttributeError: pass symbol.appendSymbolLayer(out) elif layer.outline_symbol: # outline is a symbol itself out.setStrokeStyle(Qt.NoPen) symbol.appendSymbolLayer(out) # get all layers from outline append_SymbolLayer_to_QgsSymbolLayer(symbol, layer.outline_symbol, context) else: out.setStrokeStyle(Qt.NoPen) symbol.appendSymbolLayer(out) elif isinstance(layer, ColorSymbol): out.setStrokeStyle(Qt.NoPen) symbol.appendSymbolLayer(out)