Python qgis.core.QgsField() Examples
The following are 8
code examples of qgis.core.QgsField().
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: 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 #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: break_tools.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def __init__(self,layer, tolerance, uid, errors, unlinks): QObject.__init__(self) self.layer = layer self.feat_count = self.layer.featureCount() self.tolerance = tolerance self.uid = uid self.errors = errors self.errors_features = {} self.unlinks = unlinks self.unlinked_features = [] self.unlinks_count = 0 self.ml_keys = {} self.br_keys = {} self.features = [] self.attributes = {} self.geometries = {} self.geometries_wkt = {} self.geometries_vertices = {} # create spatial index object self.spIndex = QgsSpatialIndex() self.layer_fields = [QgsField(i.name(), i.type()) for i in self.layer.dataProvider().fields()]
Example #4
Source File: Qneat3Framework.py From QNEAT3 with GNU General Public License v3.0 | 5 votes |
def calcIsoContours(self, max_dist, interval, interpolation_raster_path): featurelist = [] try: import matplotlib.pyplot as plt except: return featurelist ds_in = gdal.Open(interpolation_raster_path) band_in = ds_in.GetRasterBand(1) xsize_in = band_in.XSize ysize_in = band_in.YSize geotransform_in = ds_in.GetGeoTransform() srs = osr.SpatialReference() srs.ImportFromWkt( ds_in.GetProjectionRef() ) raster_values = band_in.ReadAsArray(0, 0, xsize_in, ysize_in) raster_values[raster_values < 0] = max_dist + 1000 #necessary to produce rectangular array from raster #nodata values get replaced by the maximum value + 1 x_pos = linspace(geotransform_in[0], geotransform_in[0] + geotransform_in[1] * raster_values.shape[1], raster_values.shape[1]) y_pos = linspace(geotransform_in[3], geotransform_in[3] + geotransform_in[5] * raster_values.shape[0], raster_values.shape[0]) x_grid, y_grid = meshgrid(x_pos, y_pos) start = interval end = interval * ceil(max_dist/interval) +interval levels = arange(start, end, interval) fid = 0 for current_level in nditer(levels): self.feedback.pushInfo("[QNEAT3Network][calcIsoContours] Calculating {}-level contours".format(current_level)) contours = plt.contourf(x_grid, y_grid, raster_values, [0, current_level], antialiased=True) for collection in contours.collections: for contour_paths in collection.get_paths(): for polygon in contour_paths.to_polygons(): x = polygon[:,0] y = polygon[:,1] polylinexy_list = [QgsPointXY(i[0], i[1]) for i in zip(x,y)] feat = QgsFeature() fields = QgsFields() fields.append(QgsField('id', QVariant.Int, '', 254, 0)) fields.append(QgsField('cost_level', QVariant.Double, '', 20, 7)) feat.setFields(fields) geom = QgsGeometry().fromPolylineXY(polylinexy_list) feat.setGeometry(geom) feat['id'] = fid feat['cost_level'] = float(current_level) featurelist.insert(0, feat) fid=fid+1 return featurelist
Example #5
Source File: Qneat3Utilities.py From QNEAT3 with GNU General Public License v3.0 | 5 votes |
def getFeatureFromPointParameter(qgs_point_xy): feature = QgsFeature() fields = QgsFields() fields.append(QgsField('point_id', QVariant.String, '', 254, 0)) feature.setFields(fields) feature.setGeometry(QgsGeometry.fromPointXY(qgs_point_xy)) feature['point_id']="Start Point" return feature
Example #6
Source File: htmlExpansionDialog.py From qgis-kmltools-plugin with GNU General Public License v2.0 | 5 votes |
def processAlgorithm(self, parameters, context, feedback): source = self.parameterAsSource(parameters, self.PrmInputLayer, context) field = self.parameterAsString(parameters, self.PrmDescriptionField, context) tags = self.parameterAsString(parameters, self.PrmExpansionTags, context).strip() type = self.parameterAsInt(parameters, self.PrmExpansionType, context) feedback.pushInfo(tags) if not field: msg = tr('Must have a valid description field') feedback.reportError(msg) raise QgsProcessingException(msg) # Set up the HTML expansion processor self.htmlProcessor = HTMLExpansionProcess(source, field, type) self.htmlProcessor.addFeature.connect(self.addFeature) # Have it generate a list of all possible expansion field names if self.PrmExpansionTags in parameters and tags != '': expansionNames = [x.strip() for x in tags.split(',')] feedback.pushInfo('{}'.format(expansionNames)) self.htmlProcessor.setDesiredFields(expansionNames) else: self.htmlProcessor.autoGenerateFileds() srcCRS = source.sourceCrs() wkbtype = source.wkbType() # Create a copy of the fields for the output fieldsout = QgsFields(source.fields()) for item in self.htmlProcessor.uniqueDesiredNames(source.fields().names()): fieldsout.append(QgsField(item, QVariant.String)) (self.sink, dest_id) = self.parameterAsSink(parameters, self.PrmOutputLayer, context, fieldsout, wkbtype, srcCRS) self.htmlProcessor.processSource() self.htmlProcessor.addFeature.disconnect(self.addFeature) return {self.PrmOutputLayer: dest_id}
Example #7
Source File: tomgrs.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 4 votes |
def processAlgorithm(self, parameters, context, feedback): source = self.parameterAsSource(parameters, self.PrmInputLayer, context) mgrs_name = self.parameterAsString(parameters, self.PrmMgrsFieldName, context).strip() precision = self.parameterAsInt(parameters, self.PrmMgrsPrecision, context) fieldsout = QgsFields(source.fields()) if fieldsout.append(QgsField(mgrs_name, QVariant.String)) is False: msg = "MGRS Field Name must be unique. There is already a field named '{}'".format(mgrs_name) feedback.reportError(msg) raise QgsProcessingException(msg) layerCRS = source.sourceCrs() (sink, dest_id) = self.parameterAsSink( parameters, self.PrmOutputLayer, context, fieldsout, source.wkbType(), layerCRS) # The input to the mgrs conversions requires latitudes and longitudes # If the layer is not EPSG:4326 we need to convert it. epsg4326 = QgsCoordinateReferenceSystem('EPSG:4326') if layerCRS != epsg4326: transform = QgsCoordinateTransform(layerCRS, epsg4326, QgsProject.instance()) total = 100.0 / source.featureCount() if source.featureCount() else 0 iterator = source.getFeatures() for cnt, feature in enumerate(iterator): if feedback.isCanceled(): break pt = feature.geometry().asPoint() if layerCRS != epsg4326: pt = transform.transform(pt) try: msg = mgrs.toMgrs(pt.y(), pt.x(), precision) except Exception: msg = '' f = QgsFeature() f.setGeometry(feature.geometry()) f.setAttributes(feature.attributes() + [msg]) sink.addFeature(f) if cnt % 100 == 0: feedback.setProgress(int(cnt * total)) return {self.PrmOutputLayer: dest_id}
Example #8
Source File: htmlExpansionDialog.py From qgis-kmltools-plugin with GNU General Public License v2.0 | 4 votes |
def accept(self): """Called when the OK button has been pressed.""" layer = self.inputLayerComboBox.currentLayer() if not layer: return newlayername = self.outputLayerLineEdit.text().strip() type = self.typeComboBox.currentIndex() # Find all the possible fields in the description area field = self.descriptionComboBox.currentField() index = layer.fields().indexFromName(field) if index == -1: self.iface.messageBar().pushMessage("", "Invalid field name", level=Qgis.Warning, duration=3) return # Set up the HTML expansion processor self.htmlProcessor = HTMLExpansionProcess(layer, field, type) self.htmlProcessor.addFeature.connect(self.addFeature) # Have it generate a list of all possible expansion field names self.htmlProcessor.autoGenerateFileds() # From the expansion processor get the list of possible expansion fields # and show a popup of them so the user can select which he wants in the output. fieldsDialog = HTMLFieldSelectionDialog(self.iface, self.htmlProcessor.fields()) fieldsDialog.exec_() # From the users selections of expansion fields, set them in the processor. # This is just a list of names. self.htmlProcessor.setDesiredFields(fieldsDialog.selected) wkbtype = layer.wkbType() layercrs = layer.crs() # Create the new list of attribute names from the original data with the unique # expansion names. fieldsout = QgsFields(layer.fields()) for item in self.htmlProcessor.uniqueDesiredNames(layer.fields().names()): fieldsout.append(QgsField(item, QVariant.String)) newLayer = QgsVectorLayer("{}?crs={}".format(QgsWkbTypes.displayString(wkbtype), layercrs.authid()), newlayername, "memory") self.dp = newLayer.dataProvider() self.dp.addAttributes(fieldsout) newLayer.updateFields() # Process each record in the input layer with the expanded entries. # The actual record is added with the 'addFeature' callback self.htmlProcessor.processSource() self.htmlProcessor.addFeature.disconnect(self.addFeature) newLayer.updateExtents() QgsProject.instance().addMapLayer(newLayer) self.close()