当前位置: 首页>>代码示例>>Python>>正文


Python core.QgsFields方法代码示例

本文整理汇总了Python中qgis.core.QgsFields方法的典型用法代码示例。如果您正苦于以下问题:Python core.QgsFields方法的具体用法?Python core.QgsFields怎么用?Python core.QgsFields使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在qgis.core的用法示例。


在下文中一共展示了core.QgsFields方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getFeatureFromPointParameter

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFields [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 
开发者ID:root676,项目名称:QNEAT3,代码行数:10,代码来源:Qneat3Utilities.py

示例2: processAlgorithm

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFields [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} 
开发者ID:NationalSecurityAgency,项目名称:qgis-kmltools-plugin,代码行数:38,代码来源:htmlExpansionDialog.py

示例3: to_shp

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFields [as 别名]
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 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:32,代码来源:utilityFunctions.py

示例4: processAlgorithm

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFields [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} 
开发者ID:NationalSecurityAgency,项目名称:qgis-latlontools-plugin,代码行数:46,代码来源:tomgrs.py

示例5: calcIsoContours

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFields [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 
开发者ID:root676,项目名称:QNEAT3,代码行数:59,代码来源:Qneat3Framework.py

示例6: accept

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFields [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() 
开发者ID:NationalSecurityAgency,项目名称:qgis-kmltools-plugin,代码行数:52,代码来源:htmlExpansionDialog.py


注:本文中的qgis.core.QgsFields方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。