Python qgis.core.QgsVectorLayer() Examples
The following are 30
code examples of qgis.core.QgsVectorLayer().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
qgis.core
, or try the search function
.
Example #1
Source File: latLonTools.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 7 votes |
def currentLayerChanged(self): layer = self.iface.activeLayer() if layer is not None: try: layer.editingStarted.disconnect(self.layerEditingChanged) except Exception: pass try: layer.editingStopped.disconnect(self.layerEditingChanged) except Exception: pass if isinstance(layer, QgsVectorLayer): layer.editingStarted.connect(self.layerEditingChanged) layer.editingStopped.connect(self.layerEditingChanged) self.enableDigitizeTool()
Example #2
Source File: Qneat3Utilities.py From QNEAT3 with GNU General Public License v3.0 | 7 votes |
def buildQgsVectorLayer(string_geomtype, string_layername, crs, feature_list, list_qgsfield): #create new vector layer from self.crs vector_layer = QgsVectorLayer(string_geomtype, string_layername, "memory") #set crs from class vector_layer.setCrs(crs) #set fields provider = vector_layer.dataProvider() provider.addAttributes(list_qgsfield) #[QgsField('fid',QVariant.Int),QgsField("origin_point_id", QVariant.Double),QgsField("iso", QVariant.Int)] vector_layer.updateFields() #fill layer with geom and attrs vector_layer.startEditing() for feat in feature_list: vector_layer.addFeature(feat, True) vector_layer.commitChanges() return vector_layer
Example #3
Source File: Utils.py From qgis-cartodb with GNU General Public License v2.0 | 7 votes |
def checkCartoDBId(layer, convert=False): """Check if layer has cartodb_id field""" new_layer = layer if convert and layer.fieldNameIndex('cartodb_id') == -1: checkTempDir() temp = tempfile.NamedTemporaryFile() error = QgsVectorFileWriter.writeAsVectorFormat(layer, temp.name, 'utf-8', None, 'ESRI Shapefile') if error == QgsVectorFileWriter.NoError: new_layer = QgsVectorLayer(temp.name + '.shp', layer.name(), 'ogr') new_layer.dataProvider().addAttributes([QgsField('cartodb_id', QVariant.Int)]) new_layer.updateFields() features = new_layer.getFeatures() i = 1 for feature in features: fid = feature.id() aid = new_layer.fieldNameIndex('cartodb_id') attrs = {aid: i} new_layer.dataProvider().changeAttributeValues({fid : attrs}) i = i + 1 new_layer.updateFeature(feature) return new_layer
Example #4
Source File: gps_tool_data_view_utils.py From stdm with GNU General Public License v2.0 | 7 votes |
def _create_temp_vector_layer(active_layer, geom_type, temp_layer_name): """ Creates a temporary vector layer in memory :param active_layer: Current active layer :param geom_type: Current active layer geometry type :param temp_layer_name: Temporary layer name :return temp_mem_layer: Temporary vector layer in memory :return data_provider: Layer data provider :rtype temp_mem_layer: Layer object :rtype data_provider: Data provider object """ active_layer_crs = str(active_layer.crs().authid()) uri = '{0}?crs={1}&field=id:integer&index=yes'.format(geom_type, active_layer_crs) temp_mem_layer = q_core.QgsVectorLayer(uri, temp_layer_name, 'memory') data_provider = temp_mem_layer.dataProvider() temp_mem_layer.startEditing() return temp_mem_layer, data_provider,
Example #5
Source File: virtual_raster.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def createReprojectedLayer(layer, crs): """ Creates a reprojected layer layer: layer used crs: crs used """ temp = QgsVectorLayer('%s?crs=%s'% ('Multipolygon', crs.authid()), 'temp', 'memory') if not layer.isValid(): raise GeoAlgorithmExecutionException('Problema ao criar camada reprojetada!') return None provider = temp.dataProvider() provider.addAttributes(layer.dataProvider().fields().toList()) temp.updateFields() coordinateTransformer = QgsCoordinateTransform(layer.crs(), crs) features = [] for feature in layer.getFeatures(): feat = QgsFeature(feature) geom = feat.geometry() geom.transform(coordinateTransformer) feat.setGeometry(geom) features.append(feat) provider.addFeatures(features) return temp
Example #6
Source File: spatialiteLayerLoader.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def getLayerByName(self, layer): """ Return the layer layer from a given layer name. :param layer: (str) layer name. :return: (QgsVectorLayer) vector layer. """ # parent class reimplementation schema = layer.split('_')[0] table = layer[len(schema) + 1:] lyrName, schema, geomColumn, tableName, srid = self.getParams(table) self.setDataSource('', layer, geomColumn, '') return QgsVectorLayer(self.uri.uri(), table, self.provider)
Example #7
Source File: shapefileLayerLoader.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def loadLayer(self, inputParam, parentNode, uniqueLoad, stylePath, domLayerDict): """ Loads a layer :param lyrName: Layer nmae :param idSubgrupo: sub group id :param uniqueLoad: boolean to mark if the layer should only be loaded once :param stylePath: path to the styles used :param domLayerDict: domain dictionary :return: """ lyrName, schema, geomColumn, tableName, srid = self.getParams(inputParam) lyr = self.checkLoaded(tableName) if uniqueLoad and lyr: return lyr self.setDataSource('', '_'.join([schema,tableName]), geomColumn, '') vlayer = QgsVectorLayer(self.uri.uri(), tableName, self.provider) QgsProject.instance().addMapLayer(vlayer, addToLegend = False) crs = QgsCoordinateReferenceSystem(int(srid), QgsCoordinateReferenceSystem.EpsgCrsId) vlayer.setCrs(crs) vlayer = self.setDomainsAndRestrictionsWithQml(vlayer) vlayer = self.setMulti(vlayer,domLayerDict) if stylePath: fullPath = self.getStyle(stylePath, tableName) if fullPath: vlayer.loadNamedStyle(fullPath, True) parentNode.addLayer(vlayer) if not vlayer.isValid(): QgsMessageLog.logMessage(vlayer.error().summary(), "DSGTools Plugin", Qgis.Critical) vlayer = self.createMeasureColumn(vlayer) return vlayer
Example #8
Source File: shapefileLayerLoader.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def getLayerByName(self, layer): """ Return the layer layer from a given layer name. :param layer: (str) layer name. :return: (QgsVectorLayer) vector layer. """ # parent class reimplementation path = os.path.join(self.abstractDb.databaseName(), "{0}.shp".format(layer)) schema = layer.split('_')[0] table = layer[len(schema) + 1:].lower() return QgsVectorLayer(path, table, "ogr")
Example #9
Source File: geopackageLayerLoader.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def getLayerByName(self, layer): """ Return the layer layer from a given layer name. :param layer: (str) table name - for GPKG it is [SCHEMA]_[CATEGORY]_[CLASS]. :return: (QgsVectorLayer) vector layer. """ # parent class reimplementation schema = layer.split('_')[0] table = layer[len(schema) + 1:] lyrName, schema, geomColumn, tableName, srid = self.getParams(table) self.setDataSource('', layer, geomColumn, '') return QgsVectorLayer("{0}|layername={1}".format(self.abstractDb.db.databaseName(), layer), table, "ogr")
Example #10
Source File: postgisDb.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def getLayerDict(self): """ Returns a dict: {'table_schema.table_name (geometryColumn):QgsVectorLayer'} """ lyrDict = dict() inputDict = self.getGeomColumnDictV2(excludeValidation = True) for key in list(inputDict.keys()): uri = self.getURIV2(inputDict[key]['tableSchema'], inputDict[key]['tableName'], inputDict[key]['geom'], '') lyr = QgsVectorLayer(uri.uri(), inputDict[key]['lyrName'], 'postgres', False) outputKey = '{0}.{1} ({2})'.format(inputDict[key]['tableSchema'], inputDict[key]['tableName'], inputDict[key]['geom']) lyrDict[outputKey] = lyr return lyrDict
Example #11
Source File: project.py From albion with GNU General Public License v3.0 | 6 votes |
def __export_raster(self, outDir, field): xspacing = self.__xspacing() yspacing = self.__yspacing() with self.connect() as con: uri = QgsDataSourceUri() uri.setConnection(con.info.host, str(con.info.port), con.info.dbname, con.info.user, con.info.password) uri.setDataSource("_albion", "current_raster", "geom") uri.setParam("checkPrimaryKeyUnicity", "0") uri.setSrid("32632") uri.setWkbType(QgsWkbTypes.Point) v = QgsVectorLayer(uri.uri(), "current_raster", "postgres") res = processing.run("gdal:rasterize", {'INPUT':v,'FIELD':field,'BURN':0,'UNITS':1,'WIDTH':xspacing,'HEIGHT':yspacing,'EXTENT':v.extent(),'NODATA':-9999,'OPTIONS':'','DATA_TYPE':5,'INIT':None,'INVERT':False,'EXTRA':'','OUTPUT':os.path.join(outDir, 'dem.tif')}) processing.run("qgis:slope", {'INPUT':res['OUTPUT'],'Z_FACTOR':1,'OUTPUT':os.path.join(outDir, 'slope.tif')}) processing.run("qgis:aspect", {'INPUT':res['OUTPUT'],'Z_FACTOR':1,'OUTPUT':os.path.join(outDir, 'aspect.tif')}) processing.run("qgis:ruggednessindex", {'INPUT':res['OUTPUT'],'Z_FACTOR':1,'OUTPUT':os.path.join(outDir, 'ruggednessindex.tif')})
Example #12
Source File: bdgexGuiManager.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def loadServiceLayer(self, legendName, service, layerList, serviceType='WMS'): urlWithParams = self.BDGExRequestHandler.get_url_string(service, layerList, serviceType) if not urlWithParams: return if serviceType == 'WMS': self.iface.addRasterLayer(urlWithParams, legendName, serviceType.lower()) if serviceType == 'WFS': vlayer = QgsVectorLayer(urlWithParams, legendName, serviceType) QgsProject.instance().addMapLayer(vlayer)
Example #13
Source File: latLonTools.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 5 votes |
def enableDigitizeTool(self): self.digitizeAction.setEnabled(False) layer = self.iface.activeLayer() if layer is not None and isinstance(layer, QgsVectorLayer) and (layer.geometryType() == QgsWkbTypes.PointGeometry) and layer.isEditable(): self.digitizeAction.setEnabled(True) else: if self.digitizerDialog is not None: self.digitizerDialog.close()
Example #14
Source File: mapToolsGuiManager.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def resetCurrentLayerSignals(self): """ Resets all signals used from current layer connected to maptools to current selection. """ if isinstance(self.currentLayer, QgsVectorLayer): # disconnect previous selection's signals, if any try: self.currentLayer.editingStarted.disconnect(self.editingStarted) self.currentLayer.editingStopped.disconnect(self.editingStopped) except: pass # now retrieve current selection and reset signal connection self.currentLayer = self.iface.mapCanvas().currentLayer() if isinstance(self.currentLayer, QgsVectorLayer): self.currentLayer.editingStarted.connect(self.editingStarted) self.currentLayer.editingStopped.connect(self.editingStopped)
Example #15
Source File: HydroSEDPluginUtils.py From WMF with GNU General Public License v3.0 | 5 votes |
def cargar_mapa_vector(self, pathMapaVector, tipo_style, color = (50,50,250), width = 0.5): #Inicia vandera de cargado y ruta del vector retornoCargarMapaVector = False pathMapaVector = pathMapaVector.strip() #verifica existencia y dado el caso carga if os.path.exists(pathMapaVector): baseNameMapaVector = os.path.basename(pathMapaVector) baseNameMapaVector = os.path.splitext(baseNameMapaVector)[0] layerMapaVector = QgsVectorLayer(pathMapaVector, baseNameMapaVector, 'ogr') QgsProject.instance().addMapLayer(layerMapaVector) if tipo_style == self.TIPO_STYLE_POLILINEA: symbols = layerMapaVector.renderer().symbols(QgsRenderContext()) symbol = symbols[0] symbol.setColor(QtGui.QColor.fromRgb(color[0],color[1],color[2])) symbol.setWidth(width) #try: # symbol.setWidth(width) #except: # symbol.setBorderWidth(width) #if layerMapVector.geometryType() == QGis.Polygon: elif tipo_style == self.TIPO_STYLE_POLIGONO: Render = layerMapaVector.renderer() mySymbol1 = QgsFillSymbol.createSimple({'color':'blue', 'color_border':'#%02x%02x%02x' % color, 'width_border':str(width), 'style':'no', 'style_border':'solid'}) Render.setSymbol(mySymbol1) layerMapaVector.triggerRepaint() retornoCargarMapaVector = layerMapaVector.isValid() return retornoCargarMapaVector, layerMapaVector
Example #16
Source File: mapillary_coverage.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
def setDefaultLayers(self): defaultContent = '{"type": "FeatureCollection", "features": []}' for ld in LAYER_LEVELS: with open(os.path.join(self.cache_dir, 'mapillary_%s.geojson' % ld), 'w') as f: f.write(defaultContent) defLyr = QgsVectorLayer(os.path.join(self.cache_dir, 'mapillary_%s.geojson' % ld),"Mapillary "+ld, "ogr") defLyr.setCrs(QgsCoordinateReferenceSystem(4326)) setattr(self, ld+'Layer', defLyr)
Example #17
Source File: utilityFunctions.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def to_shp(path, any_features_list, layer_fields, crs, name, encoding, geom_type): if path is None: if geom_type == 0: network = QgsVectorLayer('Point?crs=' + crs.toWkt(), name, "memory") else: network = QgsVectorLayer('LineString?crs=' + crs.toWkt(), name, "memory") else: fields = QgsFields() for field in layer_fields: fields.append(field) file_writer = QgsVectorFileWriter(path, encoding, fields, geom_type, crs, "ESRI Shapefile") if file_writer.hasError() != QgsVectorFileWriter.NoError: print "Error when creating shapefile: ", file_writer.errorMessage() del file_writer network = QgsVectorLayer(path, name, "ogr") pr = network.dataProvider() if path is None: pr.addAttributes(layer_fields) new_features = [] for i in any_features_list: new_feat = QgsFeature() new_feat.setFeatureId(i[0]) new_feat.setAttributes([attr[0] for attr in i[1]]) new_feat.setGeometry(QgsGeometry(QgsGeometry.fromWkt(str(i[2])))) #QgsGeometry() new_features.append(new_feat) network.startEditing() pr.addFeatures(new_features) network.commitChanges() return network
Example #18
Source File: code_list.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def layerByName(self, layerName): """ Gets vector layer from current selection. :param layerName: (str) layer name to have its layer object retrieved. :return: (QgsVectorLayer) """ l = QgsProject.instance().mapLayersByName(layerName) return l[0] if l else QgsVectorLayer()
Example #19
Source File: code_list.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def readClassFieldMap(self, preferEdgvMapping=True): """ Gets all layers with value maps. :param preferEdgvMapping: (bool) whether edgv mapping should be preferred, if exists. :return: (dict) a map from layer to list of fields with a value map. """ classFieldMap = defaultdict(dict) for layer in self.iface.mapCanvas().layers(): if not isinstance(layer, QgsVectorLayer): continue layername = layer.name() if preferEdgvMapping: fMap = self.getAllEdgvDomainsFromTableName(layername) if fMap: classFieldMap[layername] = fMap continue for field in layer.fields(): fieldName = field.name() fieldConfig = field.editorWidgetSetup().config() if 'map' not in fieldConfig or fieldName in ('UseHtml', 'IsMultiline'): continue if isinstance(fieldConfig['map'], list): for map_ in fieldConfig['map']: if fieldName not in classFieldMap[layername]: classFieldMap[layername][fieldName] = map_ else: classFieldMap[layername][fieldName].update(map_) else: classFieldMap[layername][fieldName] = fieldConfig['map'] return classFieldMap
Example #20
Source File: field_toolbox.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def getLayerFromButton(self, buttonText): """ Gets the correct layer to be used in the tool """ #edgvClass found in the dictionary (this is made using the sqlite seed) # if more than 1 button exists, it randomly generates this & middle string, why? no idea button = buttonText.split(' [')[0].replace('&', '') (category, edgvClass) = self.findReclassificationClass(button) driverName = self.widget.abstractDb.getType() if driverName == "QSQLITE": #reclassification layer name reclassificationClass = '_'.join(edgvClass.split('_')[1::]) if driverName == "QPSQL": #reclassification layer name reclassificationClass = '_'.join(edgvClass.split('.')[1::]) #getting the QgsVectorLayer to perform the reclassification reclassificationLayer = self.loadLayer(reclassificationClass) if reclassificationLayer: # self.iface.setActiveLayer(reclassificationLayer) #entering in editing mode if not reclassificationLayer.isEditable(): reclassificationLayer.startEditing() lyrAttributes = [i.name() for i in reclassificationLayer.fields()] for attr in list(self.reclassificationDict[category][edgvClass][button].keys()): if attr == 'buttonProp': continue candidateDict = self.reclassificationDict[category][edgvClass][button][attr] if isinstance(candidateDict, dict): if candidateDict['isEditable'] == '0' and attr in lyrAttributes: attrIdx = lyrAttributes.index(attr) reclassificationLayer.editFormConfig().setReadOnly(attrIdx, True) return (reclassificationLayer, category, edgvClass) # @pyqtSlot(QgsFeatureId) # @pyqtSlot(int)
Example #21
Source File: calc_contour.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def addLayers(self, layers): """ Add layer in the layer combo box layers: layer to be added """ for layer in layers: if isinstance(layer, QgsVectorLayer): self.layerCombo.addItem(layer.name())
Example #22
Source File: dsgRasterInfoTool.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def enableAssignValue(self, newTool=None, oldTool=None): self.disconnectAllSignals() layer = self.iface.mapCanvas().currentLayer() if layer and isinstance(layer, QgsVectorLayer): if layer.geometryType() == QgsWkbTypes.PointGeometry and layer.isEditable() and not self.rasterComboBox.currentLayer() is None: self.valueSetterButton.setEnabled(True) # reset editing signals self.resetEditingSignals(currentLayer=layer) else: self.valueSetterButton.setEnabled(False) if self.valueSetterButton.isChecked(): self.valueSetterButton.setChecked(False) self.activateValueSetter(False) else: self.valueSetterButton.setEnabled(False) if self.valueSetterButton.isChecked(): self.valueSetterButton.setChecked(False) self.activateValueSetter(False) self.connectAllSignals()
Example #23
Source File: dsgRasterInfoTool.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def resetEditingSignals(self, currentLayer): """ Disconnects editing signal from previously selected layer and connects it to newly selected layer. Method is called whenever currentlLayerChanged signal is emitted. """ # get previous selected layer prevLayer = self.currentLayer # update current selected layer if not currentLayer: self.currentLayer = currentLayer self.activateAlias = partial(self.activateValueSetter, True) self.deactivateAlias = partial(self.activateValueSetter, False) if prevLayer: try: # if there was a previous selection, signals must be disconnected from it before connecting to the new layer prevLayer.editingStarted.disconnect(self.activateAlias) prevLayer.editingStopped.disconnect(self.deactivateAlias) except: # in case signal is not yet connected, somehow pass # connecting signals to new layer if isinstance(self.currentLayer, QgsVectorLayer): if self.currentLayer.geometryType() == QgsWkbTypes.PointGeometry: self.currentLayer.editingStarted.connect(self.activateAlias) self.currentLayer.editingStopped.connect(self.deactivateAlias)
Example #24
Source File: inspectFeatures.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def enableTool(self, enabled = True): if enabled == None or not isinstance(enabled, QgsVectorLayer): allowed = False else: allowed = True toggled = self.inspectPushButton.isChecked() enabled = allowed and toggled self.backInspectButton.setEnabled(enabled) self.nextInspectButton.setEnabled(enabled) self.idSpinBox.setEnabled(enabled)
Example #25
Source File: styleManagerTool.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def getParametersFromLyr(self, dbName): for lyr in self.iface.mapCanvas().layers(): if isinstance(lyr, QgsVectorLayer): candidateUri = QgsDataSourceUri(lyr.dataProvider().dataSourceUri()) if candidateUri.database() == dbName or \ os.path.splitext(os.path.basename(candidateUri.uri().split('|')[0]))[0] == dbName: currLyr = lyr break dbParameters = dict() if currLyr.providerType() == 'postgres': dbParameters['host'] = candidateUri.host() dbParameters['port'] = candidateUri.port() dbParameters['user'] = candidateUri.username() dbParameters['password'] = candidateUri.password() return dbParameters, DsgEnums.DriverPostGIS elif currLyr.providerType() == 'spatialite': dbParameters['dbPath'] = candidateUri.database() return dbParameters, DsgEnums.DriverSpatiaLite elif currLyr.providerType() == 'ogr': # geopackage provider type is ogr dbParameters['dbPath'] = candidateUri.database() return dbParameters, DsgEnums.DriverGeopackage else: raise Exception(self.tr('Feature only implemented for PostGIS and Spatialite'))
Example #26
Source File: styleManagerTool.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def getDatabaseList(self): # dbList = list() dbSet = set() for lyr in self.iface.mapCanvas().layers(): if isinstance(lyr, QgsVectorLayer): candidateUri = QgsDataSourceUri(lyr.dataProvider().dataSourceUri()) dbName = candidateUri.database() # if dbName not in dbList and lyr.providerType() in ['postgres', 'spatialite']: if lyr.providerType() in ['postgres', 'spatialite']: dbSet.add(dbName) elif lyr.providerType() == 'ogr': dbName = os.path.splitext(os.path.basename(lyr.dataProvider().dataSourceUri().split('|')[0]))[0] # if db not in dbList: dbSet.add(dbName) return dbSet
Example #27
Source File: styleManagerTool.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def getLayers(self, dbName): lyrList = [] for lyr in self.iface.mapCanvas().layers(): if isinstance(lyr, QgsVectorLayer): candidateUri = QgsDataSourceUri(lyr.dataProvider().dataSourceUri()) if (candidateUri.database() == dbName and lyr.providerType() in ['postgres', 'spatialite']) \ or (os.path.splitext(os.path.basename(candidateUri.uri().split('|')[0]))[0] == dbName and lyr.providerType() == 'ogr'): lyrList.append(lyr) return lyrList
Example #28
Source File: shapeTools.py From qgis-shapetools-plugin with GNU General Public License v2.0 | 5 votes |
def currentLayerChanged(self): layer = self.iface.activeLayer() if self.previousLayer is not None: try: self.previousLayer.editingStarted.disconnect(self.layerEditingChanged) except Exception: pass try: self.previousLayer.editingStopped.disconnect(self.layerEditingChanged) except Exception: pass self.previousLayer = None if layer is not None: if isinstance(layer, QgsVectorLayer): layer.editingStarted.connect(self.layerEditingChanged) layer.editingStopped.connect(self.layerEditingChanged) self.previousLayer = layer self.enableTools()
Example #29
Source File: utilityFunctions.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def to_dblayer(dbname, user, host, port, password, schema, table_name, qgs_flds, any_features_list, crs): crs_id = str(crs.postgisSrid()) connstring = "dbname=%s user=%s host=%s port=%s password=%s" % (dbname, user, host, port, password) try: con = psycopg2.connect(connstring) cur = con.cursor() post_q_flds = {2: 'bigint[]', 6: 'numeric[]', 1: 'bool[]', 'else':'text[]'} postgis_flds_q = """""" for f in qgs_flds: f_name = '\"' + f.name() + '\"' try: f_type = post_q_flds[f.type()] except KeyError: f_type = post_q_flds['else'] postgis_flds_q += cur.mogrify("""%s %s,""", (AsIs(f_name), AsIs(f_type))) query = cur.mogrify("""DROP TABLE IF EXISTS %s.%s; CREATE TABLE %s.%s(%s geom geometry(LINESTRING, %s))""", (AsIs(schema), AsIs(table_name), AsIs(schema), AsIs(table_name), AsIs(postgis_flds_q), AsIs(crs_id))) cur.execute(query) con.commit() data = [] for (fid, attrs, wkt) in any_features_list: for idx, l_attrs in enumerate(attrs): if l_attrs: attrs[idx] = [i if i else None for i in l_attrs] if attrs[idx] == [None]: attrs[idx] = None else: attrs[idx] = [a for a in attrs[idx] if a] data.append(tuple((attrs, wkt))) args_str = ','.join( [rmv_parenthesis(cur.mogrify("%s,ST_GeomFromText(%s,%s))", (tuple(attrs), wkt, AsIs(crs_id)))) for (attrs, wkt) in tuple(data)]) ins_str = cur.mogrify("""INSERT INTO %s.%s VALUES """, (AsIs(schema), AsIs(table_name))) cur.execute(ins_str + args_str) con.commit() con.close() print "success!" uri = QgsDataSourceURI() # set host name, port, database name, username and password uri.setConnection(host, port, dbname, user, password) # set database schema, table name, geometry column and optionally uri.setDataSource(schema, table_name, "geom") return QgsVectorLayer(uri.uri(), table_name, "postgres") except psycopg2.DatabaseError, e: return e # SOURCE: ESS TOOLKIT
Example #30
Source File: acquisition.py From DsgTools with GNU General Public License v2.0 | 4 votes |
def setToolEnabled(self): layer = self.iface.activeLayer() if not isinstance(layer, QgsVectorLayer) or layer.geometryType() == QgsWkbTypes.PointGeometry or not layer.isEditable(): enabled = False else: enabled = True if not enabled and self.tool: self.tool.deactivate() if self.polygonAction: self.polygonAction.setEnabled(enabled) if self.circleAction: self.circleAction.setEnabled(enabled) return enabled