本文整理汇总了Python中qgis.core.QgsField方法的典型用法代码示例。如果您正苦于以下问题:Python core.QgsField方法的具体用法?Python core.QgsField怎么用?Python core.QgsField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qgis.core
的用法示例。
在下文中一共展示了core.QgsField方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: checkCartoDBId
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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
示例2: buildQgsVectorLayer
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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
示例3: __init__
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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()]
示例4: getFeatureFromPointParameter
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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
示例5: processAlgorithm
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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}
示例6: processAlgorithm
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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}
示例7: calcIsoContours
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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
示例8: accept
# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsField [as 别名]
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()