def _set_line_colors(self, shapes_layer): layer_routes = QgsProject.instance().mapLayersByName('routes')[0] # join lineField = 'shape_id_short' routesField = 'route_id' joinObject = QgsVectorLayerJoinInfo() joinObject.setJoinFieldName(routesField) joinObject.setTargetFieldName(lineField) joinObject.setJoinLayerId(layer_routes.id()) joinObject.setUsingMemoryCache(True) joinObject.setJoinLayer(layer_routes) shapes_layer.addJoin(joinObject) # coloring target_field = 'routes_fid' features_shape = shapes_layer.getFeatures() myCategoryList = [] colors = {} for f in features_shape: r_fid = f['routes_fid'] if r_fid not in colors: colors[r_fid] = (f['routes_route_color'], f['routes_route_short_name']) for r_fid, r_item in colors.items(): symbol = QgsSymbol.defaultSymbol(shapes_layer.geometryType()) symbol.setColor(QColor('#' + r_item[0])) myCategory = QgsRendererCategory(r_fid, symbol, r_item[1]) myCategoryList.append(myCategory) myRenderer = QgsCategorizedSymbolRenderer(target_field, myCategoryList) shapes_layer.setRenderer(myRenderer) shapes_layer.triggerRepaint() self.gtfs.setProgress(95)
def field_join(t_layer, s_layer, t_field, s_field): joinObject = QgsVectorLayerJoinInfo() joinObject.setJoinFieldName(s_field) joinObject.setTargetFieldName(t_field) joinObject.setJoinLayerId(s_layer.id()) joinObject.setUsingMemoryCache(True) joinObject.setJoinLayer(s_layer) t_layer.addJoin(joinObject)
def join(self): # join the shp layer to the excel layer, non cached # TODO: Ignore if already joined? shpLayer = layer_from_name(self.shpName) jinfo = QgsVectorLayerJoinInfo() jinfo.setJoinFieldName(self.excelKeyName) jinfo.setTargetFieldName(self.shpKeyName) jinfo.setJoinLayerId(layer_from_name(self.excelName).id()) jinfo.setUsingMemoryCache(False) jinfo.setPrefix('') for jinfo2 in shpLayer.vectorJoins(): if jinfo2 == jinfo: info("Join already exists. Will not create it again") return info("Adding join between master and slave layers") shpLayer.addJoin(jinfo)
def complete_fields(self, layer): """Join shapefile to csv and fill in the missing fields based on sub ID""" infoLyr = QgsVectorLayer(f'file:///{str(CSV)}?delimiter=,','classes','delimitedtext') QgsProject.instance().addMapLayer(infoLyr) csv_field = 'Int_SubNum' shp_field = 'HabitatSub' joinObject = QgsVectorLayerJoinInfo() joinObject.setJoinFieldName(csv_field) joinObject.setTargetFieldName(shp_field) joinObject.setJoinLayerId(infoLyr.id()) joinObject.setUsingMemoryCache(True) joinObject.setJoinLayer(infoLyr) layer.addJoin(joinObject) layer.startEditing() ha_areas = [] for feature in layer.getFeatures(): shp_fields = ['HabitatTyp', 'HabitatT_1', 'HabitatS_1', 'MMU_HA'] csv_fields = ['classes_Int_num', 'classes_Int_cls', 'classes_Int_SubCls', 'classes_MMU_'] for shp, csv in zip(shp_fields, csv_fields): f = layer.fields().indexFromName(csv) f_ = layer.fields().indexFromName(shp) layer.changeAttributeValue(feature.id(), f_, feature[f]) area_km = layer.fields().indexFromName('Area_KM') area_ha = layer.fields().indexFromName('Area_HA') orthoid_field = layer.fields().indexFromName('OrthoID') id_field = layer.fields().indexFromName('Id') layer.changeAttributeValue(feature.id(), area_km, feature.geometry().area() / 10**6) layer.changeAttributeValue(feature.id(), area_ha, feature.geometry().area() / 10**4) ha_areas.append(feature.geometry().area() / 10**4) layer.changeAttributeValue(feature.id(), orthoid_field, feature[0]) layer.changeAttributeValue(feature.id(), id_field, feature.id()) layer.removeJoin(infoLyr.id()) QgsProject.instance().removeMapLayer(infoLyr) fields_to_drop = set(['RuleID', 'Shape_Leng', 'Shape_Area']) field_ids = [] for field in layer.fields(): if field.name() in fields_to_drop: field_ids.append(layer.fields().indexFromName(field.name())) layer.dataProvider().deleteAttributes(field_ids) layer.commitChanges()
def add_joins(self, feedback): """ Add all joins between tables. """ for definition in self.attribute_joins: definition = dict(definition) join_layer = definition['join_layer'] layer_add_join = definition['layer_add_join'] feedback.pushInfo('Ajout de la jointure {} sur {}'.format( join_layer, layer_add_join)) definition['join_layer'] = self.input_layers[join_layer] definition['layer_add_join'] = self.input_layers[layer_add_join] for join in definition['layer_add_join'].vectorJoins(): if definition['join_layer'] == join.joinLayer(): definition['layer_add_join'].removeJoin( join.joinLayer().id()) feedback.pushDebugInfo( 'Removing pre-existing join between {} and {}'.format( definition['layer_add_join'].name(), definition['join_layer'].name())) join_habitat = QgsVectorLayerJoinInfo() join_habitat.setJoinFieldName(definition['join_field_name']) join_habitat.setJoinLayerId(definition['join_layer'].id()) join_habitat.setTargetFieldName(definition['target_field_name']) join_habitat.setPrefix(definition['prefix']) join_habitat.setJoinLayer(definition['join_layer']) if 'block_list' in definition: if Qgis.QGIS_VERSION_INT >= 31400: join_habitat.setJoinFieldNamesBlockList( definition['block_list']) else: join_habitat.setJoinFieldNamesBlackList( definition['block_list']) if not definition['layer_add_join'].addJoin(join_habitat): raise Exception('Join not added {}'.format( definition['join_field_name'])) self.success_join += 1
def joinTables(self): d, f = self.lyrPair() for k, v in d.items(): target = QgsProject.instance().mapLayer(k) layerToJoin = QgsProject.instance().mapLayer(v) fieldToJoin = QgsProject.instance() symb = QgsVectorLayerJoinInfo() symb.setJoinFieldName('id_feature') symb.setTargetFieldName('id') symb.setJoinLayerId(layerToJoin.id()) symb.setUsingMemoryCache(True) symb.setEditable(True) symb.setDynamicFormEnabled(True) symb.setUpsertOnEdit(True) symb.setPrefix('') symb.setJoinFieldNamesSubset([ 'ocultar', 'legenda', 'tamanhotxt', 'justtxt', 'orient_txt', 'orient_simb', 'offset_txt', 'offset_simb', 'prioridade', 'offset_txt_x', 'offset_txt_y' ]) symb.setJoinLayer(layerToJoin) target.addJoin(symb)
def joinTables(self): d, f = self.lyrPair() for k, v in d.items(): target = QgsProject.instance().mapLayer(k) layerToJoin = QgsProject.instance().mapLayer(v) """ # tests for previous joined layers - under research i = QgsProject.instance().mapLayers().values() for layer in i: fh_lyr = layer joinsInfo = fh_lyr.vectorJoins() if joinsInfo != 0: QMessageBox.critical(iface.mainWindow(), "Error", "Previously Joins already exists! Please remove joins and try again.") break # ask for remove previous joins. use removeJoinTables() else: """ # target.removeJoin(layerToJoin.id()) fieldToJoin = QgsProject.instance() symb = QgsVectorLayerJoinInfo() symb.setJoinFieldName('id_feature') symb.setTargetFieldName('id') symb.setJoinLayerId(layerToJoin.id()) symb.setUsingMemoryCache(True) symb.setEditable(True) symb.setDynamicFormEnabled(True) symb.setUpsertOnEdit(True) symb.setPrefix('') symb.setJoinFieldNamesSubset([ 'ocultar', 'legenda', 'tamanhotxt', 'justtxt', 'orient_txt', 'orient_simb', 'offset_txt', 'offset_simb', 'prioridade', 'offset_txt_x', 'offset_txt_y' ]) symb.setJoinLayer(layerToJoin) target.addJoin(symb) layerToJoin.startEditing() target.triggerRepaint()
def processAlgorithm(self, parameters, context, feedback): t_file = self.parameterAsVectorLayer( parameters, self.FILE_TABLE, context ) t_troncon = self.parameterAsVectorLayer( parameters, self.SEGMENTS_TABLE, context ) t_obs = self.parameterAsVectorLayer( parameters, self.OBSERVATIONS_TABLE, context ) t_regard = self.parameterAsVectorLayer( parameters, self.MANHOLES_TABLE, context ) g_regard = self.parameterAsVectorLayer( parameters, self.GEOM_MANHOLES, context ) g_troncon = self.parameterAsVectorLayer( parameters, self.GEOM_SEGMENT, context ) g_obs = self.parameterAsVectorLayer( parameters, self.GEOM_OBSERVATION, context ) v_regard = self.parameterAsVectorLayer( parameters, self.VIEW_MANHOLES_GEOLOCALIZED, context ) # define variables variables = context.project().customVariables() variables['itv_rerau_t_file'] = t_file.id() variables['itv_rerau_t_troncon'] = t_troncon.id() variables['itv_rerau_t_obs'] = t_obs.id() variables['itv_rerau_t_regard'] = t_regard.id() variables['itv_rerau_g_regard'] = g_regard.id() variables['itv_rerau_g_troncon'] = g_troncon.id() variables['itv_rerau_g_obs'] = g_obs.id() context.project().setCustomVariables(variables) # define relations relations = [ { 'id': 'fk_obs_id_file', 'name': tr('Link File - Observation'), 'referencingLayer': t_obs.id(), 'referencingField': 'id_file', 'referencedLayer': t_file.id(), 'referencedField': 'id' }, { 'id': 'fk_regard_id_file', 'name': tr('Link File - Manhole'), 'referencingLayer': t_regard.id(), 'referencingField': 'id_file', 'referencedLayer': t_file.id(), 'referencedField': 'id' }, { 'id': 'fk_troncon_id_file', 'name': tr('Link File - Pipe segment'), 'referencingLayer': t_troncon.id(), 'referencingField': 'id_file', 'referencedLayer': t_file.id(), 'referencedField': 'id' }, { 'id': 'fk_obs_id_troncon', 'name': tr('Link Pipe segment - Observation'), 'referencingLayer': t_obs.id(), 'referencingField': 'id_troncon', 'referencedLayer': t_troncon.id(), 'referencedField': 'id' }, { 'id': 'fk_regard_id_geom_regard', 'name': tr('Link Manhole inspection - Reference'), 'referencingLayer': t_regard.id(), 'referencingField': 'id_geom_regard', 'referencedLayer': g_regard.id(), 'referencedField': 'id' }, { 'id': 'fk_troncon_id_geom_trononc', 'name': tr('Link Pipe segment inspection - Reference'), 'referencingLayer': t_troncon.id(), 'referencingField': 'id_geom_troncon', 'referencedLayer': g_troncon.id(), 'referencedField': 'id' } ] relation_manager = context.project().relationManager() for rel_def in relations: feedback.pushInfo( 'Link: {}'.format(rel_def['name']) ) rel = QgsRelation() rel.setId(rel_def['id']) rel.setName(rel_def['name']) rel.setReferencingLayer(rel_def['referencingLayer']) rel.setReferencedLayer(rel_def['referencedLayer']) rel.addFieldPair( rel_def['referencingField'], rel_def['referencedField'] ) rel.setStrength(QgsRelation.Association) relation_manager.addRelation(rel) feedback.pushInfo( 'Count relations {}'.format( len(relation_manager.relations()) ) ) joins = [ { 'layer': t_obs, 'targetField': 'id_troncon', 'joinLayer': t_troncon, 'joinField': 'id', 'fieldNamesSubset': ['ack'] }, { 'layer': g_obs, 'targetField': 'id', 'joinLayer': t_obs, 'joinField': 'id', 'fieldNamesSubset': [] } ] for j_def in joins: layer = j_def['layer'] join = QgsVectorLayerJoinInfo() join.setJoinFieldName(j_def['joinField']) join.setJoinLayerId(j_def['joinLayer'].id()) join.setTargetFieldName(j_def['targetField']) if j_def['fieldNamesSubset']: join.setJoinFieldNamesSubset(j_def['fieldNamesSubset']) join.setUsingMemoryCache(False) join.setPrefix('') join.setEditable(False) join.setCascadedDelete(False) join.setJoinLayer(j_def['joinLayer']) layer.addJoin(join) layer.updateFields() # load styles styles = [ { 'layer': t_file, 'namedStyles': [ { 'file': 'itv_file_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_file_actions.qml', 'type': QgsMapLayer.Actions } ] }, { 'layer': t_troncon, 'namedStyles': [ { 'file': 'itv_troncon_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_troncon_table.qml', 'type': QgsMapLayer.AttributeTable } ] }, { 'layer': t_obs, 'namedStyles': [ { 'file': 'itv_obs_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_obs_table.qml', 'type': QgsMapLayer.AttributeTable } ] }, { 'layer': t_regard, 'namedStyles': [ { 'file': 'itv_regard_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_regard_forms.qml', 'type': QgsMapLayer.Forms }, { 'file': 'itv_regard_table.qml', 'type': QgsMapLayer.AttributeTable } ] }, { 'layer': g_regard, 'namedStyles': [ { 'file': 'itv_geom_regard_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_geom_regard_symbology.qml', 'type': QgsMapLayer.Symbology } ] }, { 'layer': g_troncon, 'namedStyles': [ { 'file': 'itv_geom_troncon_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_geom_troncon_symbology.qml', 'type': QgsMapLayer.Symbology }, { 'file': 'itv_geom_troncon_actions.qml', 'type': QgsMapLayer.Actions } ] }, { 'layer': g_obs, 'namedStyles': [ { 'file': 'itv_geom_obs_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_geom_obs_symbology.qml', 'type': QgsMapLayer.Symbology } ] }, { 'layer': v_regard, 'namedStyles': [ { 'file': 'itv_view_regard_fields.qml', 'type': QgsMapLayer.Fields }, { 'file': 'itv_view_regard_symbology.qml', 'type': QgsMapLayer.Symbology }, { 'file': 'itv_view_regard_labeling.qml', 'type': QgsMapLayer.Labeling } ] } ] for style in styles: layer = style['layer'] for n_style in style['namedStyles']: layer.loadNamedStyle( resources_path('styles', n_style['file']), categories=n_style['type'] ) # layer.saveStyleToDatabase('style', 'default style', True, '') layer.triggerRepaint() # Creation de la symbologie g_obs g_obs_rules = ( 'BAA', 'BAB', 'BAC', 'BAD', 'BAE', 'BAF', 'BAG', 'BAH', 'BAI', 'BAJ', 'BAK', 'BAL', 'BAM', 'BAN', 'BAO', 'BAP', 'BBA', 'BBB', 'BBC', 'BBD', 'BBE', 'BBF', 'BBG', 'BBH', 'BCA', 'BCB', 'BCC', 'BDA', 'BDB', 'BDC', 'BDD', 'BDE', 'BDF', 'BDG' ) g_obs_rule_descs = { 'BAA': 'Déformation', 'BAB': 'Fissure', 'BAC': 'Rupture/Effondrement', 'BAD': 'Elt maçonnerie', 'BAE': 'Mortier manquant', 'BAF': 'Dégradation de surface', 'BAG': 'Branchement pénétrant', 'BAH': 'Raccordement défectueux', 'BAI': 'Joint étanchéité apparent', 'BAJ': 'Déplacement d\'assemblage', 'BAK': 'Défaut de révêtement', 'BAL': 'Réparation défectueuse', 'BAM': 'Défaut soudure', 'BAN': 'Conduite poreuse', 'BAO': 'Sol visible', 'BAP': 'Trou visible', 'BBA': 'Racines', 'BBB': 'Dépots Adhérents', 'BBC': 'Dépôts', 'BBD': 'Entrée de terre', 'BBE': 'Autres obstacles', 'BBF': 'Infiltration', 'BBG': 'Exfiltration', 'BBH': 'Vermine', 'BCA': 'Raccordement', 'BCB': 'Réparation', 'BCC': 'Courbure de collecteur', 'BDA': 'Photographie générale', 'BDB': 'Remarque générale', 'BDC': 'Inspection abandonnée', 'BDD': 'Niveau d\'eau', 'BDE': 'Ecoulement dans une canlisation entrante', 'BDF': 'Atmosphère canalisation', 'BDG': 'Perte de visibilité' } g_obs_rootrule = QgsRuleBasedRenderer.Rule(None) rendering_pass_idx = len(g_obs_rules) for rule in g_obs_rules: # get svg path svg_path = resources_path('styles', 'img_obs', rule + '.svg') # create svg symbol layer svg_symbol_layer = QgsSvgMarkerSymbolLayer(svg_path) svg_symbol_layer.setRenderingPass(rendering_pass_idx) # create white square symbol layer for the backend simple_symbol_layer = QgsSimpleMarkerSymbolLayer( shape=QgsSimpleMarkerSymbolLayerBase.Circle, size=svg_symbol_layer.size(), color=QColor('white'), strokeColor=QColor('white') ) simple_symbol_layer.setRenderingPass(rendering_pass_idx) # create marker svg_marker = QgsMarkerSymbol() # set the backend symbol layer svg_marker.changeSymbolLayer(0, simple_symbol_layer) # add svg symbol layer svg_marker.appendSymbolLayer(svg_symbol_layer) # create rule svg_rule = QgsRuleBasedRenderer.Rule( svg_marker, 0, 10000, QgsExpression.createFieldEqualityExpression('a', rule), rule ) if rule in g_obs_rule_descs: svg_rule.setLabel(g_obs_rule_descs[rule]) svg_rule.setDescription('{}: {}'.format( rule, g_obs_rule_descs[rule] )) # add rule g_obs_rootrule.appendChild(svg_rule) rendering_pass_idx -= 1 g_obs_rootrule.appendChild( QgsRuleBasedRenderer.Rule( QgsMarkerSymbol.createSimple( { 'name': 'circle', 'color': '#0000b2', 'outline_color': '#0000b2', 'size': '1' } ), 0, 10000, 'ELSE', 'Autres' ) ) g_obs.setRenderer(QgsRuleBasedRenderer(g_obs_rootrule)) feedback.pushInfo('Project has been setup') return {}
def run(self): project_id = self.settings.value("project/id") epsg = self.settings.value("project/epsg") locale = QSettings().value('locale/userLocale')[ 0:2] # this is for multilingual legends # If locale is different to frence or italian, german will be used. # Otherwise we get into troubles with the legends, e.g. locale = "en" # but # there is no english legend (qml file). if locale == "fr": pass elif locale == "it": pass else: locale = "de" if not project_id: self.message_bar.pushCritical( "Error", _translate("VeriSO_V+D_FP2", "project_id not set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_V+D_FP2", "FixpunkteKategorie2", None) group += " (" + str(project_id) + ")" # Lagefixpunkte 2 layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP2", "LFP2 Nachführung", None), "featuretype": "fixpunktekategorie2_lfp2nachfuehrung", "geom": "perimeter", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } # Visibility and if legend and/or groupd should be collapsed can # be set with parameters in the self.layer_loader.load() # method: # load(layer, visibility=True, collapsed_legend=False, # collapsed_group=False) vlayer_lfp2_nf = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP2", "LFP2", None), "featuretype": "fixpunktekategorie2_lfp2", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "fixpunkte/lfp2.qml" } vlayer_lfp2 = self.layer_loader.load(layer) # Join two layers (lfp2 and lfp2nachfuehrung) lfp2_field = "entstehung" lfp2_nf_field = "ogc_fid" join_obj = QgsVectorLayerJoinInfo() join_obj.setJoinLayerId(vlayer_lfp2_nf.id()) join_obj.setJoinFieldName(lfp2_nf_field) join_obj.setTargetFieldName(lfp2_field) join_obj.setUsingMemoryCache(True) join_obj.setPrefix("lfp2_nf_") vlayer_lfp2.addJoin(join_obj) # This is how WMS layer work. layer = { "type": "wms", "title": _translate("VeriSO_V+D_FP2", "LFP2 Schweiz (WMS)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.swisstopo.fixpunkte-lfp2", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) # Höhenfixpunkte 2 layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP2", "HFP2 Nachführung", None), "featuretype": "fixpunktekategorie2_hfp2nachfuehrung", "geom": "perimeter", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } vlayer_hfp2_nf = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP2", "HFP2", None), "featuretype": "fixpunktekategorie2_hfp2", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "fixpunkte/hfp2.qml" } vlayer_hfp2 = self.layer_loader.load(layer) # Join two layers (hfp2 and hfp2nachfuehrung) hfp2_field = "entstehung" hfp2_nf_field = "ogc_fid" join_obj = QgsVectorLayerJoinInfo() join_obj.setJoinLayerId(vlayer_hfp2_nf.id()) join_obj.setJoinFieldName(hfp2_nf_field) join_obj.setTargetFieldName(hfp2_field) join_obj.setUsingMemoryCache(True) join_obj.setPrefix("hfp2_nf_") vlayer_hfp2.addJoin(join_obj) layer = { "type": "wms", "title": _translate("VeriSO_V+D_FP2", "HFP2 Schweiz (WMS)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.swisstopo.fixpunkte-hfp2", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) # Business as usual: Gemeindegrenzen layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP2", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "global_qml/gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer) # Change map extent. # Bug (?) in QGIS: http://hub.qgis.org/issues/10980 # Closed for the lack of feedback. Upsi... # Still a problem? (sz / 2015-04-12) if gemgrelayer: rect = gemgrelayer.extent() rect.scale(5) self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() # Sometimes it does make much more sense # to zoom to maximal extent: # self.iface.mapCanvas().zoomToFullExtent() except Exception: QApplication.restoreOverrideCursor() exc_type, exc_value, exc_traceback = sys.exc_info() self.message_bar.pushMessage( "Error", str(traceback.format_exc(exc_traceback)), level=Qgis.Critical, duration=0) QApplication.restoreOverrideCursor()
def run(self): project_id = self.settings.value("project/id") epsg = self.settings.value("project/epsg") self.project_dir = self.settings.value("project/projectdir") self.project_id = self.settings.value("project/id") locale = QSettings().value('locale/userLocale')[ 0:2] # this is for multilingual legends # If locale is different to frence or italian, german will be used. # Otherwise we get into troubles with the legends, e.g. locale = "en" # but # there is no english legend (qml file). if locale == "fr": pass elif locale == "it": pass else: locale = "de" if not project_id: self.message_bar.pushCritical("Error", _translate("VeriSO_V+D_FP3", "project_id not set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_V+D_FP3", "FixpunkteKategorie3", None) group += " (" + str(project_id) + ")" layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP3", "Toleranzstufen", None), "featuretype": "tseinteilung_toleranzstufe", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "tseinteilung/toleranzstufe_" + locale + ".qml" } # Visibility and if legend and/or groupd should be collapsed can # be set with parameters in the self.layer_loader.load() # method: # load(layer, visibility=True, collapsed_legend=False, # collapsed_group=False) vlayer = self.layer_loader.load(layer) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP3", "LFP3 Nachführung", None), "featuretype": "fixpunktekategorie3_lfp3nachfuehrung", "geom": "perimeter", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } vlayer_lfp3_nf = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP3", "LFP3", None), "featuretype": "fixpunktekategorie3_lfp3", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "fixpunkte/lfp3_" + locale + ".qml" } vlayer_lfp3 = self.layer_loader.load(layer) # Join two layers (lfp3 and lfp3nachfuehrung) lfp3_field = "entstehung" lfp3_nf_field = "ogc_fid" join_obj = QgsVectorLayerJoinInfo() join_obj.setJoinLayerId(vlayer_lfp3_nf.id()) join_obj.setJoinFieldName(lfp3_nf_field) join_obj.setTargetFieldName(lfp3_field) join_obj.setUsingMemoryCache(True) join_obj.setPrefix("lfp3_nf_") vlayer_lfp3.addJoin(join_obj) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP3", "LFP3 ausserhalb " "Gemeinde", None), "featuretype": "t_lfp3_ausserhalb_gemeinde", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "fixpunkte/lfp3ausserhalb.qml" } vlayer = self.layer_loader.load(layer) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP3", "LFP3 pro TS", None), "featuretype": "t_lfp3_pro_ts", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } vlayer_lfp3_pro_ts = self.layer_loader.load(layer) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP3", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "global_qml/gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer) # Change map extent. # Bug (?) in QGIS: http://hub.qgis.org/issues/10980 # Closed for the lack of feedback. Upsi... # Still a problem? (sz / 2015-04-12) # sz / 2015-04-20: # Aaaah: still a problem. Some really strange combination of # checked/unchecked-order-of-layers-thing? # If wms is addes after gemgre then is scales (rect.scale(5))?! # So it seems that the last added layer HAS TO BE unchecked? # No not exactly. Only if a wms is added before? # rect.scale(5) has no effect? # I reopened the ticket / 2015-04-20 / sz if gemgrelayer: rect = gemgrelayer.extent() rect.scale(5) self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() # Sometimes it does make much more sense # to zoom to maximal extent: # self.iface.mapCanvas().zoomToFullExtent() self.export_to_excel(vlayer_lfp3_pro_ts) except Exception: QApplication.restoreOverrideCursor() exc_type, exc_value, exc_traceback = sys.exc_info() self.message_bar.pushMessage("Error", str( traceback.format_exc(exc_traceback)), level=Qgis.Critical, duration=0) QApplication.restoreOverrideCursor()
def processAlgorithm(self, parameters, context, feedback): self.layers = self.parameterAsLayerList(parameters, self.INPUTS, context) self.drop = self.parameterAsBool(parameters, self.DROP_EXISTING_JOINS, context) # return {} # def postProcess(self, context, feedback): # # We try to use postProcess instead of processAlgorithm to propagate joins in the project. # layers = self.layers # drop = self.drop total = len(self.layers) failed = [] feedback.pushDebugInfo('{} layer(s) have been selected.'.format(total)) for i, layer in enumerate(self.layers): # Just trying on more time to get the real layer layer = context.project().mapLayer(layer.id()) if not layer: feedback.reportError( 'Layer {} has not been found in the project. Skipping…'. format(layer.name())) continue feedback.pushInfo('Processing layer \'{}\' with ID {}'.format( layer.name(), layer.id())) joined_fields = [] if self.drop: for vector_join in layer.vectorJoins(): feedback.pushInfo('Removing join \'{}\''.format( vector_join.joinFieldName())) layer.removeJoin(vector_join.joinLayerId()) for field in layer.fields(): widget = field.editorWidgetSetup() if not widget.type() == 'ValueRelation': continue config = widget.config() target_layer = config['Layer'] target_field = config['Key'] source_field = field.name() join_layer = context.project().mapLayer(target_layer) if not join_layer: feedback.reportError( "The layer \"{}\" linked to the field \"{}\" has not been found in the project. " "Skipping this ValueRelation…".format( target_layer, source_field)) continue join = QgsVectorLayerJoinInfo() join.setJoinLayerId(target_layer) join.setJoinFieldName(target_field) join.setTargetFieldName(source_field) join.setUsingMemoryCache(True) feedback.pushInfo( 'Adding join on \'{}\' with prefix \'{}\''.format( field.name(), self.prefix.format(join_layer.name()))) join.setPrefix(self.prefix.format(join_layer.name())) if not layer.addJoin(join): failed.append(layer.name()) feedback.reportError( 'Failed to add the join on {} {}'.format( layer.name(), field.name())) continue for join_field in join_layer.fields(): joined_fields.append( self.prefix.format(join_layer.name()) + join_field.name()) # Uncheck WMS feedback.pushInfo('Unchecking WMS fields') # if Qgis.QGIS_VERSION_INT < 31800: layer.setExcludeAttributesWms(joined_fields) # else: # # Fix for QGIS >= 3.16 # for field in joined_fields: # layer.setFieldConfigurationFlag( # layer.fields().indexFromName(field), QgsField.HideFromWms, True) feedback.pushDebugInfo(', '.join(layer.excludeAttributesWms())) # Uncheck WFS for ids id_fields = [ f for f in joined_fields if f.endswith('_fid') or f.endswith('_id') ] feedback.pushInfo('Unchecking WFS fields') # if Qgis.QGIS_VERSION_INT < 31800: layer.setExcludeAttributesWfs(id_fields) # else: # # Fix for QGIS >= 3.16 # for field in id_fields: # layer.setFieldConfigurationFlag( # layer.fields().indexFromName(field), QgsField.HideFromWfs, True) feedback.pushDebugInfo(', '.join(layer.excludeAttributesWfs())) feedback.setProgress((i + 1) / total * 100) # layer.reload() It does nothing, not enough to propagate the join if failed: msg = 'Some joins failed to be added for : {}'.format( ', '.join(failed)) raise QgsProcessingException(msg) feedback.reportError( 'Everything went fine, BUT you must save your project and reopen it. Joins, WMS and WFS are ' 'not appearing otherwise.') return {}