def test_join(self): joinLayer = createJoinLayer() joinLayer2 = createJoinLayer() QgsMapLayerRegistry.instance().addMapLayers([joinLayer, joinLayer2]) layer = createLayerWithOnePoint() join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) join2 = QgsVectorJoinInfo() join2.targetFieldName = "fldint" join2.joinLayerId = joinLayer2.id() join2.joinFieldName = "y" join2.memoryCache = True join2.prefix = "custom-prefix_" layer.addJoin(join2) flds = layer.pendingFields() assert len(flds) == 6 assert flds[2].name() == "joinlayer_x" assert flds[3].name() == "joinlayer_z" assert flds[4].name() == "custom-prefix_x" assert flds[5].name() == "custom-prefix_z" assert flds.fieldOrigin(0) == QgsFields.OriginProvider assert flds.fieldOrigin(2) == QgsFields.OriginJoin assert flds.fieldOrigin(3) == QgsFields.OriginJoin assert flds.fieldOriginIndex(0) == 0 assert flds.fieldOriginIndex(2) == 0 assert flds.fieldOriginIndex(3) == 2 f = QgsFeature() fi = layer.getFeatures() assert fi.nextFeature(f) attrs = f.attributes() assert len(attrs) == 6 assert attrs[0] == "test" assert attrs[1] == 123 assert attrs[2] == "foo" assert attrs[3] == 321 assert not fi.nextFeature(f) f2 = layer.getFeatures(QgsFeatureRequest(f.id())).next() assert len(f2.attributes()) == 6 assert f2[2] == "foo" assert f2[3] == 321
def test_join(self): joinLayer = createJoinLayer() joinLayer2 = createJoinLayer() QgsMapLayerRegistry.instance().addMapLayers([joinLayer, joinLayer2]) layer = createLayerWithOnePoint() join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) join2 = QgsVectorJoinInfo() join2.targetFieldName = "fldint" join2.joinLayerId = joinLayer2.id() join2.joinFieldName = "y" join2.memoryCache = True join2.prefix = "custom-prefix_" layer.addJoin(join2) flds = layer.pendingFields() self.assertEquals(len(flds), 6) self.assertEquals(flds[2].name(), "joinlayer_x") self.assertEquals(flds[3].name(), "joinlayer_z") self.assertEquals(flds[4].name(), "custom-prefix_x") self.assertEquals(flds[5].name(), "custom-prefix_z") self.assertEquals(flds.fieldOrigin(0), QgsFields.OriginProvider) self.assertEquals(flds.fieldOrigin(2), QgsFields.OriginJoin) self.assertEquals(flds.fieldOrigin(3), QgsFields.OriginJoin) self.assertEquals(flds.fieldOriginIndex(0), 0) self.assertEquals(flds.fieldOriginIndex(2), 0) self.assertEquals(flds.fieldOriginIndex(3), 2) f = QgsFeature() fi = layer.getFeatures() self.assertTrue(fi.nextFeature(f)) attrs = f.attributes() self.assertEquals(len(attrs), 6) self.assertEquals(attrs[0], "test") self.assertEquals(attrs[1], 123) self.assertEquals(attrs[2], "foo") self.assertEquals(attrs[3], 321) self.assertFalse(fi.nextFeature(f)) f2 = next(layer.getFeatures(QgsFeatureRequest(f.id()))) self.assertEquals(len(f2.attributes()), 6) self.assertEquals(f2[2], "foo") self.assertEquals(f2[3], 321)
def test_join(self): joinLayer = createJoinLayer() joinLayer2 = createJoinLayer() QgsMapLayerRegistry.instance().addMapLayers([joinLayer, joinLayer2]) layer = createLayerWithOnePoint() join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) join2 = QgsVectorJoinInfo() join2.targetFieldName = "fldint" join2.joinLayerId = joinLayer2.id() join2.joinFieldName = "y" join2.memoryCache = True join2.prefix = "custom-prefix_" layer.addJoin(join2) flds = layer.pendingFields() self.assertEquals(len(flds), 6) self.assertEquals(flds[2].name(), "joinlayer_x") self.assertEquals(flds[3].name(), "joinlayer_z") self.assertEquals(flds[4].name(), "custom-prefix_x") self.assertEquals(flds[5].name(), "custom-prefix_z") self.assertEquals(flds.fieldOrigin(0), QgsFields.OriginProvider) self.assertEquals(flds.fieldOrigin(2), QgsFields.OriginJoin) self.assertEquals(flds.fieldOrigin(3), QgsFields.OriginJoin) self.assertEquals(flds.fieldOriginIndex(0), 0) self.assertEquals(flds.fieldOriginIndex(2), 0) self.assertEquals(flds.fieldOriginIndex(3), 2) f = QgsFeature() fi = layer.getFeatures() self.assertTrue(fi.nextFeature(f)) attrs = f.attributes() self.assertEquals(len(attrs), 6) self.assertEquals(attrs[0], "test") self.assertEquals(attrs[1], 123) self.assertEquals(attrs[2], "foo") self.assertEquals(attrs[3], 321) self.assertFalse(fi.nextFeature(f)) f2 = layer.getFeatures(QgsFeatureRequest(f.id())).next() self.assertEquals(len(f2.attributes()), 6) self.assertEquals(f2[2], "foo") self.assertEquals(f2[3], 321)
def test_join(self): joinLayer = createJoinLayer() joinLayer2 = createJoinLayer() QgsMapLayerRegistry.instance().addMapLayers([joinLayer, joinLayer2]) layer = createLayerWithOnePoint() join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) join2 = QgsVectorJoinInfo() join2.targetFieldName = "fldint" join2.joinLayerId = joinLayer2.id() join2.joinFieldName = "y" join2.memoryCache = True join2.prefix = "custom-prefix_" layer.addJoin(join2) flds = layer.pendingFields() assert len(flds) == 6 assert flds[2].name() == "joinlayer_x" assert flds[3].name() == "joinlayer_z" assert flds[4].name() == "custom-prefix_x" assert flds[5].name() == "custom-prefix_z" assert flds.fieldOrigin(0) == QgsFields.OriginProvider assert flds.fieldOrigin(2) == QgsFields.OriginJoin assert flds.fieldOrigin(3) == QgsFields.OriginJoin assert flds.fieldOriginIndex(0) == 0 assert flds.fieldOriginIndex(2) == 0 assert flds.fieldOriginIndex(3) == 2 f = QgsFeature() fi = layer.getFeatures() assert fi.nextFeature(f) == True attrs = f.attributes() assert len(attrs) == 6 assert attrs[0] == "test" assert attrs[1] == 123 assert attrs[2] == "foo" assert attrs[3] == 321 assert fi.nextFeature(f) == False f2 = layer.getFeatures(QgsFeatureRequest(f.id())).next() assert len(f2.attributes()) == 6 assert f2[2] == "foo" assert f2[3] == 321
def test_joined_layers_conversion(self): v1 = QgsVectorLayer("Point?field=id:integer&field=b_id:integer&field=c_id:integer&field=name:string", "A", "memory") self.assertEqual(v1.isValid(), True) v2 = QgsVectorLayer("Point?field=id:integer&field=bname:string&field=bfield:integer", "B", "memory") self.assertEqual(v2.isValid(), True) v3 = QgsVectorLayer("Point?field=id:integer&field=cname:string", "C", "memory") self.assertEqual(v3.isValid(), True) QgsProject.instance().addMapLayers([v1, v2, v3]) joinInfo = QgsVectorJoinInfo() joinInfo.targetFieldName = "b_id" joinInfo.joinLayerId = v2.id() joinInfo.joinFieldName = "id" #joinInfo.prefix = "B_"; v1.addJoin(joinInfo) self.assertEqual(len(v1.fields()), 6) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id())) # with a field subset v1.removeJoin(v2.id()) joinInfo.setJoinFieldNamesSubset(["bname"]) v1.addJoin(joinInfo) self.assertEqual(len(v1.fields()), 5) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id())) joinInfo.setJoinFieldNamesSubset(None) # add a table prefix to the join v1.removeJoin(v2.id()) joinInfo.prefix = "BB_" v1.addJoin(joinInfo) self.assertEqual(len(v1.fields()), 6) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS BB_bname, j1.bfield AS BB_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id())) joinInfo.prefix = "" v1.removeJoin(v2.id()) v1.addJoin(joinInfo) # add another join joinInfo2 = QgsVectorJoinInfo() joinInfo2.targetFieldName = "c_id" joinInfo2.joinLayerId = v3.id() joinInfo2.joinFieldName = "id" v1.addJoin(joinInfo2) self.assertEqual(len(v1.fields()), 7) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), ('SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield, j2.cname AS C_cname FROM {} AS t ' + 'LEFT JOIN {} AS j1 ON t."b_id"=j1."id" ' + 'LEFT JOIN {} AS j2 ON t."c_id"=j2."id"').format(v1.id(), v2.id(), v3.id())) QgsProject.instance().removeMapLayers([v1.id(), v2.id(), v3.id()])
def test_joined_layers_conversion(self): v1 = QgsVectorLayer("Point?field=id:integer&field=b_id:integer&field=c_id:integer&field=name:string", "A", "memory") self.assertEqual(v1.isValid(), True) v2 = QgsVectorLayer("Point?field=id:integer&field=bname:string&field=bfield:integer", "B", "memory") self.assertEqual(v2.isValid(), True) v3 = QgsVectorLayer("Point?field=id:integer&field=cname:string", "C", "memory") self.assertEqual(v3.isValid(), True) QgsMapLayerRegistry.instance().addMapLayers([v1, v2, v3]) joinInfo = QgsVectorJoinInfo() joinInfo.targetFieldName = "b_id" joinInfo.joinLayerId = v2.id() joinInfo.joinFieldName = "id" #joinInfo.prefix = "B_"; v1.addJoin(joinInfo) self.assertEqual(len(v1.fields()), 6) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id())) # with a field subset v1.removeJoin(v2.id()) joinInfo.setJoinFieldNamesSubset(["bname"]) v1.addJoin(joinInfo) self.assertEqual(len(v1.fields()), 5) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id())) joinInfo.setJoinFieldNamesSubset(None) # add a table prefix to the join v1.removeJoin(v2.id()) joinInfo.prefix = "BB_" v1.addJoin(joinInfo) self.assertEqual(len(v1.fields()), 6) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS BB_bname, j1.bfield AS BB_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id())) joinInfo.prefix = "" v1.removeJoin(v2.id()) v1.addJoin(joinInfo) # add another join joinInfo2 = QgsVectorJoinInfo() joinInfo2.targetFieldName = "c_id" joinInfo2.joinLayerId = v3.id() joinInfo2.joinFieldName = "id" v1.addJoin(joinInfo2) self.assertEqual(len(v1.fields()), 7) df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1) self.assertEqual(df.query(), ('SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield, j2.cname AS C_cname FROM {} AS t ' + 'LEFT JOIN {} AS j1 ON t."b_id"=j1."id" ' + 'LEFT JOIN {} AS j2 ON t."c_id"=j2."id"').format(v1.id(), v2.id(), v3.id())) QgsMapLayerRegistry.instance().removeMapLayers([v1.id(), v2.id(), v3.id()])
def openProject(): from PyQt4.QtCore import * import qgis from qgis.core import QgsMapLayerRegistry, QgsVectorJoinInfo for layer in QgsMapLayerRegistry.instance().mapLayers().values(): # If a layer name = postcode, define it as a variable called 'shp' if layer.name() == "postcode": qgis.utils.iface.setActiveLayer(layer) shp = qgis.utils.iface.activeLayer() for layer in QgsMapLayerRegistry.instance().mapLayers().values(): # If a layer name = CRVsignups, define it as a variable called 'csv' if layer.name() == "CRVsignups": qgis.utils.iface.setActiveLayer(layer) csv = qgis.utils.iface.activeLayer() # Set up join parameters shpField='pcode' csvField='pcode' joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = csv.id() joinObject.joinFieldName = csvField joinObject.targetFieldName = shpField shp.addJoin(joinObject) # Define fields to update and joined fields to copy values from ip1 = shp.fieldNameIndex('Total') ip1_join = shp.fieldNameIndex('CRVsignups_Total') shp.startEditing() for feat in shp.getFeatures(): shp.changeAttributeValue(feat.id(), ip1, feat.attributes()[ip1_join]) shp.commitChanges()
def applySymbology(self): self.getConnection() vlayer = qgis.utils.iface.mapCanvas().currentLayer() if vlayer == None: return fields = vlayer.dataProvider().fields() classField = None for f in fields: if f.name() == "classtype": classField = 'classtype' elif f.name() == "result": classField = 'result' print classField class_loaded = False for layer in QgsMapLayerRegistry.instance().mapLayers().values(): if layer.name() == "class": vlayerClass = layer class_loaded = True if not class_loaded: uriSubClass = QgsDataSourceURI() uriSubClass.setConnection(self.serverName, "5432", self.database, self.usr , self.pw) uriSubClass.setDataSource("classification", "class", None, "", "id") vlayerClass = QgsVectorLayer(uriSubClass.uri(), "class", "postgres") QgsMapLayerRegistry.instance().addMapLayer(vlayerClass) for field in fields: index = vlayer.fieldNameIndex(field.name()) if field.name() == classField: vlayer.editFormConfig().setWidgetType(index, 'ValueRelation') vlayer.editFormConfig().setWidgetConfig(index, {'Layer': vlayerClass.id(), 'Key': 'id', 'Value': 'classname'}) useJoin = True if useJoin: joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = vlayerClass.id() joinObject.joinFieldName = 'id' joinObject.targetFieldName = classField joinObject.memoryCache = True vlayer.addJoin(joinObject) self.join.append(joinObject) categories = [] iter = vlayerClass.getFeatures() for feature in iter: classname = feature['classname'] color = QColor(feature['red'], feature['green'], feature['blue']) sym = QgsSymbolV2.defaultSymbol(vlayer.geometryType()) sym.setColor(QColor(color)) category = QgsRendererCategoryV2(classname, sym, classname) categories.append(category) field = "class_classname" renderer = QgsCategorizedSymbolRendererV2(field, categories) vlayer.setRendererV2(renderer) qgis.utils.iface.messageBar().pushMessage("Information", "Editor widget set", level = qgis.gui.QgsMessageBar.INFO, duration = 5) qgis.utils.iface.setActiveLayer(vlayer)
def joinLayer(self, targetlayer, pkfield, sourcelayer, fkfield): """ Join the results of the SQL Server query to the pg layer """ joinInfo = QgsVectorJoinInfo() joinInfo.targetFieldName = pkfield joinInfo.joinLayerId = sourcelayer.id() joinInfo.joinFieldName = fkfield joinInfo.memoryCache = True targetlayer.addJoin(joinInfo) targetlayer.updateFields() return targetlayer
def addCsv(self): """Crea una capa a partir de un archivo CSV, y une la información que contiene esta, con la tabla de atributos de la capa de secciones, la cual tendrá que existir, para que se pueda realizar esta operación. """ try: shp = QgsMapLayerRegistry.instance().mapLayersByName( "secciones")[0] except IndexError: self.errorDialog( u'No se encontró la capa de secciones.', u'Asegurate de agregarla con la opción de Cargar fondos.') return sheet = None field_names = [field.name() for field in shp.pendingFields()] csvDialog = CSVDialog(field_names) result = csvDialog.exec_() if result and csvDialog.getLayer(): # print csvDialog.getSelectedColumns() sheet = csvDialog.getLayer() QgsMapLayerRegistry.instance().addMapLayer(sheet) #Columnas del archivo CSV columns = csvDialog.getSelectedColumns() #Filtra las columnas existentes, para evitar información duplicada field_names = [field.name() for field in shp.pendingFields()] columns = [ col for col in columns if 'csv' + col not in field_names ] if columns == []: #No hay columnas nuevas para unir return shpField = csvDialog.getJoinFieldTarget() csvField = csvDialog.getJoinField() joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = sheet.id() joinObject.joinFieldName = csvField joinObject.targetFieldName = shpField joinObject.setJoinFieldNamesSubset(columns) joinObject.memoryCache = True shp.addJoin(joinObject)
def test_JoinUsingExpression2(self): """ test joining a layer using a virtual field (the other way!) """ joinLayer = QgsVectorLayer( "Point?field=x:string&field=y:integer&field=z:integer", "joinlayer", "memory") pr = joinLayer.dataProvider() f1 = QgsFeature() f1.setAttributes(["foo", 246, 321]) f2 = QgsFeature() f2.setAttributes(["bar", 456, 654]) self.assertTrue(pr.addFeatures([f1, f2])) joinLayer.addExpressionField('"y"/2', QgsField('exp1', QVariant.LongLong)) layer = QgsVectorLayer( "Point?field=fldtxt:string&field=fldint:integer", "addfeat", "memory") pr = layer.dataProvider() f = QgsFeature() f.setAttributes(["test", 123]) self.assertTrue(pr.addFeatures([f])) QgsMapLayerRegistry.instance().addMapLayers([layer, joinLayer]) join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "exp1" join.memoryCache = True layer.addJoin(join) f = QgsFeature() fi = layer.getFeatures() self.assertTrue(fi.nextFeature(f)) attrs = f.attributes() self.assertEqual(attrs[0], "test") self.assertEqual(attrs[1], 123) self.assertEqual(attrs[2], "foo") self.assertEqual(attrs[3], 246) self.assertEqual(attrs[4], 321) self.assertFalse(fi.nextFeature(f)) QgsMapLayerRegistry.instance().removeMapLayers( [layer.id(), joinLayer.id()])
def test_join(self): joinLayer = createJoinLayer() QgsMapLayerRegistry.instance().addMapLayers([joinLayer]) layer = createLayerWithOnePoint() join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) flds = layer.pendingFields() assert len(flds) == 4 assert flds[2].name() == "joinlayer_x" assert flds[3].name() == "joinlayer_z" assert flds.fieldOrigin(0) == QgsFields.OriginProvider assert flds.fieldOrigin(2) == QgsFields.OriginJoin assert flds.fieldOrigin(3) == QgsFields.OriginJoin assert flds.fieldOriginIndex(0) == 0 assert flds.fieldOriginIndex(2) == 0 assert flds.fieldOriginIndex(3) == 2 f = QgsFeature() fi = layer.getFeatures() assert fi.nextFeature(f) == True attrs = f.attributes() assert len(attrs) == 4 assert attrs[0].toString() == "test" assert attrs[1].toInt()[0] == 123 assert attrs[2].toString() == "foo" assert attrs[3].toInt()[0] == 321 assert fi.nextFeature(f) == False f2 = QgsFeature() assert layer.featureAtId(f.id(), f2) assert len(f2.attributes()) == 4 assert f2[2].toString() == "foo" assert f2[3].toInt()[0] == 321
def pos(self, layer, csv_cols, csv_field, shp_cols, shp_field): """Este método se encarga de realizar la unión entre el archivo CSV que se cargo, y la tabla de atributos de self.shp. :param layer: Capa del archivo CSV. :type layer: QgsVectorLayer :param csv_cols: Lista con las columnas de la capa CSV que se van a unir. :type csv_cols: Lista str :param csv_field: Campo de la capa CSV que se va a usar como columna de unión. :type csv_field: str :param shp_cols: Lista de columnas de la tabla de atributos de self.shp que se van a unir. :type shp_cols: Lista str :param shp_field: Campo de la capa self.shp que se va a usar como columna de unión. :type shp_field: str """ sheet = layer manager.add_layers([sheet]) #Columnas del archivo CSV columns = csv_cols #Columnas del archivo shp field_names = shp_cols #Filtra las columnas existentes, para evitar información duplicada columns = [col for col in columns if 'csv_' + col not in field_names] # print columns if columns == []: #No hay columnas nuevas para unir return joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = sheet.id() joinObject.joinFieldName = csv_field joinObject.targetFieldName = shp_field joinObject.setJoinFieldNamesSubset(columns) joinObject.memoryCache = True self.shp.addJoin(joinObject)
def test_JoinUsingExpression2(self): """ test joining a layer using a virtual field (the other way!) """ joinLayer = QgsVectorLayer( "Point?field=x:string&field=y:integer&field=z:integer", "joinlayer", "memory") pr = joinLayer.dataProvider() f1 = QgsFeature() f1.setAttributes(["foo", 246, 321]) f2 = QgsFeature() f2.setAttributes(["bar", 456, 654]) self.assertTrue(pr.addFeatures([f1, f2])) joinLayer.addExpressionField('"y"/2', QgsField('exp1', QVariant.LongLong)) layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", "addfeat", "memory") pr = layer.dataProvider() f = QgsFeature() f.setAttributes(["test", 123]) self.assertTrue(pr.addFeatures([f])) QgsProject.instance().addMapLayers([layer, joinLayer]) join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "exp1" join.memoryCache = True layer.addJoin(join) f = QgsFeature() fi = layer.getFeatures() self.assertTrue(fi.nextFeature(f)) attrs = f.attributes() self.assertEqual(attrs[0], "test") self.assertEqual(attrs[1], 123) self.assertEqual(attrs[2], "foo") self.assertEqual(attrs[3], 246) self.assertEqual(attrs[4], 321) self.assertFalse(fi.nextFeature(f)) QgsProject.instance().removeMapLayers([layer.id(), joinLayer.id()])
def test_JoinUsingFeatureRequestExpression(self): """ test requesting features using a filter expression which requires joined columns """ joinLayer = QgsVectorLayer( "Point?field=x:string&field=y:integer&field=z:integer", "joinlayer", "memory") pr = joinLayer.dataProvider() f1 = QgsFeature() f1.setAttributes(["foo", 123, 321]) f2 = QgsFeature() f2.setAttributes(["bar", 124, 654]) self.assertTrue(pr.addFeatures([f1, f2])) layer = QgsVectorLayer( "Point?field=fldtxt:string&field=fldint:integer", "addfeat", "memory") pr = layer.dataProvider() f1 = QgsFeature() f1.setAttributes(["test", 123]) f2 = QgsFeature() f2.setAttributes(["test", 124]) self.assertTrue(pr.addFeatures([f1, f2])) QgsMapLayerRegistry.instance().addMapLayers([layer, joinLayer]) join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) f = QgsFeature() fi = layer.getFeatures(QgsFeatureRequest().setFlags( QgsFeatureRequest.SubsetOfAttributes).setFilterExpression( 'joinlayer_z=654')) self.assertTrue(fi.nextFeature(f)) self.assertEqual(f['fldint'], 124) self.assertEqual(f['joinlayer_z'], 654) QgsMapLayerRegistry.instance().removeMapLayers( [layer.id(), joinLayer.id()])
def execute_layers_join(layer, layer_field, column_header, fk_layer, fk_field): """ Joins two layers with specified field. :param layer: The destination layer of the merge. :type layer: QgsVectorLayer :param layer_field: The source layer of the merge. :type layer_field: String :param fk_layer: The foreign key layer object. :type fk_layer: QgsVectorLayer :param fk_field: The foreign key layer field name. :type fk_field: String :return: :rtype: """ join = QgsVectorJoinInfo() join.joinLayerId = fk_layer.id() join.joinFieldName = 'id' join.setJoinFieldNamesSubset([fk_field]) join.targetFieldName = layer_field join.memoryCache = True join.prefix = u'{} '.format(column_header) layer.addJoin(join)
def test_JoinUsingFeatureRequestExpression(self): """ test requesting features using a filter expression which requires joined columns """ joinLayer = QgsVectorLayer( "Point?field=x:string&field=y:integer&field=z:integer", "joinlayer", "memory") pr = joinLayer.dataProvider() f1 = QgsFeature() f1.setAttributes(["foo", 123, 321]) f2 = QgsFeature() f2.setAttributes(["bar", 124, 654]) self.assertTrue(pr.addFeatures([f1, f2])) layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", "addfeat", "memory") pr = layer.dataProvider() f1 = QgsFeature() f1.setAttributes(["test", 123]) f2 = QgsFeature() f2.setAttributes(["test", 124]) self.assertTrue(pr.addFeatures([f1, f2])) QgsProject.instance().addMapLayers([layer, joinLayer]) join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) f = QgsFeature() fi = layer.getFeatures(QgsFeatureRequest().setFlags(QgsFeatureRequest.SubsetOfAttributes).setFilterExpression('joinlayer_z=654')) self.assertTrue(fi.nextFeature(f)) self.assertEqual(f['fldint'], 124) self.assertEqual(f['joinlayer_z'], 654) QgsProject.instance().removeMapLayers([layer.id(), joinLayer.id()])
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 == "fr": pass elif locale == "it": pass else: locale = "de" if not project_id: self.message_bar.pushCritical( "Error", _translate("VeriSO_PNF_Bestockt", "project_id not set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_PNF_Bahn", "Lagekontrolle - Bestockte Flaeche", None) group += " (" + str(project_id) + ")" layer = { "type": "wms", "title": _translate("VeriSO_PNF_bestockt", "Orthofoto CIR", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto.cir", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_bestockt", "Orthofoto RGB", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto_rgb", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_bestockt", "DTM Hangneigung", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.hangneigung", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_bestockt", "DOM", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.dom_relief", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_bestockt", "DTM", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.dtm_relief", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_bestockte_ortho.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, #"style": "bodenbedeckung/projboflaeche_color.qml" } eoeolayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_bestockte_ortho.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() for feature in eoeolayer.getFeatures(): joinIdx = feature.fieldNameIndex("ogc_fid") for t_feature in eoflayer.getFeatures(): targetIdx = t_feature.fieldNameIndex("flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_bestockte_ortho.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "EO.Punktelement", None), "featuretype": "einzelobjekte_punktelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_pk_andere.qml" } eopklayer = self.layer_loader.load(layer, True, False) if eopklayer <> False: self.iface.legendInterface().setLayerVisible(eopklayer, True) if eoeolayer <> False and eopklayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("tid") targetProvider = eopklayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("punktelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "tid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "punktelement_von" joinInfo.memoryCache = True eopklayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "Waldplan (AWJF)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "waldplan_awjf", "geom": "wkb_geometry", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "sogis/waldplan_awjf.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "LI.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "TS-Einteilung", None), "featuretype": "tseinteilung_toleranzstufe", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "ts/ts_einteilung.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "Kontrollraster (Planeinteilung)", None), "featuretype": "t_kontrollraster_plan_bestockt", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": False, "group": group, "style": "kontrollraster/kontrollraster.qml" } vlayer = self.layer_loader.load(layer, False, False) if vlayer <> False: self.iface.legendInterface().setLayerVisible(vlayer, False) provider = vlayer.dataProvider() provider.attributeIndexes() ogc_fid_idx = provider.fieldNameIndex("ogc_fid") vlayer.setEditorWidgetV2(0, "Hidden") plannummer_idx = provider.fieldNameIndex("plannummer") vlayer.setEditorWidgetV2(2, "Hidden") kontrolliert_idx = provider.fieldNameIndex("kontrolliert") vlayer.setEditorWidgetV2(1, "CheckBox") vlayer.setEditorWidgetV2Config( 1, { 'fieldEditable': "1", 'UncheckedState': 'f', 'CheckedState': 't' }) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_bestockt", "Kontrollraster", None), "featuretype": "t_kontrollraster_bestockte_500", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": False, "group": group, "style": "kontrollraster/kontrollraster.qml" } vlayer = self.layer_loader.load(layer, True, False) if vlayer <> False: self.iface.legendInterface().setLayerVisible(vlayer, True) provider = vlayer.dataProvider() provider.attributeIndexes() ogc_fid_idx = provider.fieldNameIndex("ogc_fid") vlayer.setEditorWidgetV2(0, "Hidden") kontrolliert_idx = provider.fieldNameIndex("kontrolliert") vlayer.setEditorWidgetV2(1, "CheckBox") vlayer.setEditorWidgetV2Config( 1, { 'fieldEditable': "1", 'UncheckedState': 'f', 'CheckedState': 't' }) if gemgrelayer: rect = gemgrelayer.extent() self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() 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=QgsMessageBar.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 == "fr": pass elif locale == "it": pass else: locale = "de" if not project_id: self.message_bar.pushCritical( "Error", _translate("VeriSO_PNF_Bestockt", "project_id not " "set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_PNF_Bestockt", "Checklayer - Bestockte Flaeche", None) group += " (" + str(project_id) + ")" layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_bestockte_bbplan.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } eoeolayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_bestockte_ortho.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eoflayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex( "flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_bestockte_ortho.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt", "LI.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt", "BB.Wald in TS2", None), "featuretype": "t_wald_in_ts2", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "checks/checklayer_punkt.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt", "EO.schmale_bestockte_Flaeche", None), "featuretype": "t_schm_best_flaeche", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "checks/checklayer_polygon.qml" } vlayer = self.layer_loader.load(layer, True, False) 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=QgsMessageBar.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 == "fr": pass elif locale == "it": pass else: locale = "de" if not project_id: self.message_bar.pushCritical("Error", _translate("VeriSO_PNF_Gewaesser", "project_id not set", None) ) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_PNF_Gewaesser", "Lagekontrolle - Gewaesser", None) group += " (" + str(project_id) + ")" layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "Orthofoto CIR", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto.cir", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "Orthofoto RGB", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto_rgb", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "DTM Hangneigung", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.hangneigung", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "DTM", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.dtm", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "Gewässer", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.afu.fliessgewaesser.netz", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group, "style": "gewaesser/gewisso.qml" } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_gewaesser_ortho.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } eoeolayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_gewaesser_ortho.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() for feature in eoeolayer.getFeatures(): joinIdx=feature.fieldNameIndex("ogc_fid") for t_feature in eoflayer.getFeatures(): targetIdx=t_feature.fieldNameIndex("flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_gewaesser_ortho.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Punktelement", None), "featuretype": "einzelobjekte_punktelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_pk_andere.qml" } eopklayer = self.layer_loader.load(layer, True, False) if eopklayer <> False: self.iface.legendInterface().setLayerVisible(eopklayer, True) if eoeolayer <> False and eopklayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eopklayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("punktelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "punktelement_von" joinInfo.memoryCache = True eopklayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "BB.Symbole", None), "featuretype": "v_bodenbedeckung_boflaechesymbol", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_symbole.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Symbole", None), "featuretype": "t_eo_symbole", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_symbole.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "LI.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "BB.Objektname", None), "featuretype": "v_bb_objektnamen", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_objektnamen.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Objektname", None), "featuretype": "v_eo_objektnamen", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_objektnamen.qml" } vlayer = self.layer_loader.load(layer, True, False) if gemgrelayer: rect = gemgrelayer.extent() self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() 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=QgsMessageBar.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 == "fr": pass elif locale == "it": pass else: locale = "de" if not project_id: self.message_bar.pushCritical( "Error", _translate("VeriSO_PNF_Seltene_Objekte", "project_id not set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_PNF_Seltene_Objekte", "Lagekontrolle - Seltene Objekte", None) group += " (" + str(project_id) + ")" layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Orthofoto CIR", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto.cir", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Orthofoto RGB", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto_rgb", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "DTM Hangneigung", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.hangneigung", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_seltene_objekte_ortho.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } eoeolayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_seltene_objekte_ortho.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() for feature in eoeolayer.getFeatures(): joinIdx = feature.fieldNameIndex("ogc_fid") for t_feature in eoflayer.getFeatures(): targetIdx = t_feature.fieldNameIndex("flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_seltene_objekte_ortho.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Punktelement", None), "featuretype": "einzelobjekte_punktelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_pk_seltene_objekte_ortho.qml" } eopklayer = self.layer_loader.load(layer, True, False) if eopklayer <> False: self.iface.legendInterface().setLayerVisible(eopklayer, True) if eoeolayer <> False and eopklayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eopklayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("punktelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "punktelement_von" joinInfo.memoryCache = True eopklayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Abbaustellen (AfU)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "abbaustellen_afu", "geom": "wkb_geometry", "key": "gid", "sql": "", "readonly": True, "group": group, "style": "sogis/abbaustellen_afu.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Flachmoor (AfU)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "flachmoor_afu", "geom": "wkb_geometry", "key": "gid", "sql": "", "readonly": True, "group": group, "style": "sogis/flachmoor_afu.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Freileitungen (ARP)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "freileitungen_arp", "geom": "wkb_geometry", "key": "gid", "sql": "", "readonly": True, "group": group, "style": "sogis/freileitungen_arp.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "LI.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Flachmoor (BAFU)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bafu.bundesinventare-flachmoore", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Hochmoor (BAFU)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bafu.bundesinventare-hochmoore", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Mobilfunkantennen GSM", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bakom.mobil-antennenstandorte-gsm", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Mobilfunkantennen UMTS", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bakom.mobil-antennenstandorte-umts", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Radio- und Fernsehsender", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bakom.radio-fernsehsender", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) if gemgrelayer: rect = gemgrelayer.extent() self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() 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=QgsMessageBar.CRITICAL, duration=0) QApplication.restoreOverrideCursor()
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_FP1", "project_id not set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_V+D_FP1", "FixpunkteKategorie1", None) group += " (" + str(project_id) + ")" # Lagefixpunkte 1 layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP1", "LFP1 Nachführung", None), "featuretype": "fixpunktekatgrie1_lfp1nachfuehrung", "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_lfp1_nf = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP1", "LFP1", None), "featuretype": "fixpunktekatgrie1_lfp1", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "fixpunkte/lfp2.qml" } vlayer_lfp1 = self.layer_loader.load(layer) # Join two layers (lfp1 and lfp1nachfuehrung) lfp1_field = "entstehung" lfp1_nf_field = "ogc_fid" join_obj = QgsVectorJoinInfo() join_obj.joinLayerId = vlayer_lfp1_nf.id() join_obj.joinFieldName = lfp1_nf_field join_obj.targetFieldName = lfp1_field join_obj.memoryCache = True join_obj.prefix = "lfp1_nf_" vlayer_lfp1.addJoin(join_obj) # This is how WMS layer work. layer = { "type": "wms", "title": _translate("VeriSO_V+D_FP1", "LFP1 Schweiz (WMS)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.swisstopo.fixpunkte-lfp1", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) # Höhenfixpunkte 1 layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP1", "HFP1 Nachführung", None), "featuretype": "fixpunktekatgrie1_hfp1nachfuehrung", "geom": "perimeter", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } vlayer_hfp1_nf = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_FP1", "HFP1", None), "featuretype": "fixpunktekatgrie1_hfp1", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "fixpunkte/hfp2.qml" } vlayer_hfp1 = self.layer_loader.load(layer) # Join two layers (hfp1 and hfp1nachfuehrung) hfp1_field = "entstehung" hfp1_nf_field = "ogc_fid" join_obj = QgsVectorJoinInfo() join_obj.joinLayerId = vlayer_hfp1_nf.id() join_obj.joinFieldName = hfp1_nf_field join_obj.targetFieldName = hfp1_field join_obj.memoryCache = True join_obj.prefix = "hfp1_nf_" vlayer_hfp1.addJoin(join_obj) layer = { "type": "wms", "title": _translate("VeriSO_V+D_FP1", "HFP1 Schweiz (WMS)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.swisstopo.fixpunkte-hfp1", "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_FP1", "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=QgsMessageBar.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": "fixpunktekatgrie3_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": "fixpunktekatgrie3_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 = QgsVectorJoinInfo() join_obj.joinLayerId = vlayer_lfp3_nf.id() join_obj.joinFieldName = lfp3_nf_field join_obj.targetFieldName = lfp3_field join_obj.memoryCache = True join_obj.prefix = "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=QgsMessageBar.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 == "fr": pass elif locale == "it": pass else: locale = "de" if not project_id: self.message_bar.pushCritical( "Error", _translate("VeriSO_PNF_Seltene_Objekte", "project_id not " "set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_PNF_Seltene_Objekte", "Checklayer - Seltene Objekte", None) group += " (" + str(project_id) + ")" layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_bb_plan.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } eoeolayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_bb_plan.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() for feature in eoeolayer.getFeatures(): joinIdx = feature.fieldNameIndex("ogc_fid") for t_feature in eoflayer.getFeatures(): targetIdx = t_feature.fieldNameIndex("flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_bb_plan.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Li.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "BB.Boeschungsbauwerk", None), "featuretype": "t_boeschungbwerke", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "checks/checklayer_punkt.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Brunnen", None), "featuretype": "t_brunnen", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "checks/checklayer_punkt.qml" } vlayer = self.layer_loader.load(layer, True, False) QApplication.restoreOverrideCursor() # Export feature count in excel file. try: settings = QSettings("CatAIS", "VeriSO") module_name = settings.value("project/appmodule") provider = settings.value("project/provider") dbhost = settings.value("project/dbhost") db_port = settings.value("project/dbport") dbname = settings.value("project/dbname") dbschema = settings.value("project/dbschema") dbuser = settings.value("project/dbuser") dbpwd = settings.value("project/dbpwd") projectId = settings.value("project/id") project_dir = settings.value("project/projectdir") db = QSqlDatabase.addDatabase("QPSQL", "SelteneObjekte") db.setDatabaseName(dbname) db.setHostName(dbhost) db.setUserName(dbuser) db.setPassword(dbpwd) if db.open() == False: QMessageBox.critical( None, "QGeoApp", QCoreApplication.translate( "QGeoApp", "Could not open database:\n") + str(db.lastError().driverText())) return filename = QDir.convertSeparators( QDir.cleanPath( os.path.join(project_dir, "seltene_objekte.xlsx"))) # Create excel file. wb = pycel.Workbook(filename) #wb.country_code = 41 style1 = wb.add_format({'bold': True}) style2 = wb.add_format({'italic': True}) # Bodenbedeckung sql = "SELECT CASE WHEN anz IS NULL THEN 0 ELSE anz END, bb_art.itfcode as art, bb_art.ilicode as art_txt " sql += "FROM (" sql += "SELECT count(art) as anz, art_txt, art" sql += " FROM " + dbschema + ".bodenbedeckung_boflaeche" sql += " WHERE art IN (7, 9, 19, 20, 21, 22, 30, 33, 35, 36, 37, 38, 39, 40)" sql += " GROUP BY art, art_txt" sql += ") bb" sql += " FULL JOIN " + dbschema + ".bodenbedeckung_bbart bb_art ON bb_art.itfcode = bb.art" sql += " WHERE bb_art.itfcode IN (7, 9, 19, 20, 21, 22, 30, 33, 35, 36, 37, 38, 39, 40)" sql += " ORDER BY bb_art.itfcode;" query = db.exec_(sql) if query.isActive() == False: QMessageBox.critical( None, "QGeoApp", QCoreApplication.translate( "QGeoApp", "Error occured while fetching data informations.")) return ws = wb.add_worksheet(u'BB seltene Objekte') ws.paper_size_code = 8 ws.print_centered_vert = False ws.print_centered_horz = False ws.top_margin = 1.0 ws.left_margin = 1.0 ws.bottom_margin = 1.0 ws.portrait = True ws.write(0, 0, str("BB seltene Objekte: "), style1) ws.write(0, 1, str(projectId)) ws.write(2, 0, str("Art")) ws.write(2, 1, str("Art-Text")) ws.write(2, 2, str("Anzahl")) i = 0 record = query.record() anz_index = record.indexOf("anz") art_index = record.indexOf("art") art_txt_index = record.indexOf("art_txt") while query.next(): anz = str(query.value(anz_index)) art = str(query.value(art_index)) art_txt = str(query.value(art_txt_index)) ws.write(3 + i, 0, art) ws.write(3 + i, 1, art_txt) ws.write(3 + i, 2, anz) i += 1 # Einzelobjekte sql = "SELECT CASE WHEN anz IS NULL THEN 0 ELSE anz END, eo_art.itfcode as art, eo_art.ilicode as art_txt" sql += " FROM" sql += " (" sql += " SELECT count(art) as anz, art_txt, art" sql += " FROM " + dbschema + ".einzelobjekte_einzelobjekt" sql += " WHERE art IN (9, 14, 15, 16, 17, 18, 23, 30, 31, 35, 36, 37, 38, 40, 42)" sql += " GROUP BY art, art_txt" sql += ") eo" sql += " FULL JOIN " + dbschema + ".einzelobjekte_eoart eo_art ON eo_art.itfcode = eo.art" sql += " WHERE eo_art.itfcode IN (9, 14, 15, 16, 17, 18, 23, 30, 31, 35, 36, 37, 38, 40, 42)" sql += " ORDER BY eo_art.itfcode" query = db.exec_(sql) if query.isActive() == False: QMessageBox.critical( None, "QGeoApp", QCoreApplication.translate( "QGeoApp", "Error occured while fetching data informations.")) return ws = wb.add_worksheet(u'EO seltene Objekte') ws.paper_size_code = 8 ws.print_centered_vert = False ws.print_centered_horz = False ws.top_margin = 1.0 ws.left_margin = 1.0 ws.bottom_margin = 1.0 ws.portrait = True ws.write(0, 0, str("EO seltene Objekte: "), style1) ws.write(0, 1, projectId) ws.write(2, 0, str("Art")) ws.write(2, 1, str("Art-Text")) ws.write(2, 2, str("Anzahl")) i = 0 record = query.record() while query.next(): anz = str(query.value(record.indexOf("anz"))) art = str(query.value(record.indexOf("art"))) art_txt = str(query.value(record.indexOf("art_txt"))) ws.write(3 + i, 0, art) ws.write(3 + i, 1, art_txt) if int(anz) > 0: ws.write(3 + i, 2, anz, style1) else: ws.write(3 + i, 2, anz) i += 1 #file = QDir.convertSeparators(QDir.cleanPath(project_dir + os.sep + "seltene_objekte.xls")) try: wb.close() QMessageBox.information( None, "", QCoreApplication.translate( "QGeoAppModule.PNF", "File written:\n") + filename) except IOError: QMessageBox.warning( None, "", QCoreApplication.translate( "QGeoAppModule.PNF", "File <b>not</b> written!<br>") + filename) return db.close() except: QMessageBox.critical( None, "QGeoApp", QCoreApplication.translate( "QGeoApp", "Error exporting data from database to excel.")) 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=QgsMessageBar.CRITICAL, duration=0) QApplication.restoreOverrideCursor()
assert f.geometry().asPoint() == QgsPoint(100,200) assert f["fldtxt"] == "test" assert f["fldint"] == 123 assert fi.nextFeature(f) == False def test_join(self): joinLayer = createJoinLayer() QgsMapLayerRegistry.instance().addMapLayers([joinLayer]) layer = createLayerWithOnePoint() join = QgsVectorJoinInfo() join.targetFieldName = "fldint" join.joinLayerId = joinLayer.id() join.joinFieldName = "y" join.memoryCache = True layer.addJoin(join) flds = layer.pendingFields() assert len(flds) == 4 assert flds[2].name() == "joinlayer_x" assert flds[3].name() == "joinlayer_z" assert flds.fieldOrigin(0) == QgsFields.OriginProvider assert flds.fieldOrigin(2) == QgsFields.OriginJoin assert flds.fieldOrigin(3) == QgsFields.OriginJoin assert flds.fieldOriginIndex(0) == 0 assert flds.fieldOriginIndex(2) == 0 assert flds.fieldOriginIndex(3) == 2