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


Python core.QgsVectorLayer方法代码示例

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


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

示例1: currentLayerChanged

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

示例2: checkCartoDBId

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

示例3: buildQgsVectorLayer

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

示例4: _create_temp_vector_layer

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

示例5: __export_raster

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsVectorLayer [as 别名]
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')}) 
开发者ID:Oslandia,项目名称:albion,代码行数:18,代码来源:project.py

示例6: currentLayerChanged

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

示例7: getParametersFromLyr

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsVectorLayer [as 别名]
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')) 
开发者ID:dsgoficial,项目名称:DsgTools,代码行数:26,代码来源:styleManagerTool.py

示例8: resetEditingSignals

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsVectorLayer [as 别名]
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) 
开发者ID:dsgoficial,项目名称:DsgTools,代码行数:27,代码来源:dsgRasterInfoTool.py

示例9: enableAssignValue

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

示例10: resetCurrentLayerSignals

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsVectorLayer [as 别名]
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) 
开发者ID:dsgoficial,项目名称:DsgTools,代码行数:18,代码来源:mapToolsGuiManager.py

示例11: enableDigitizeTool

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

示例12: cargar_mapa_vector

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

示例13: setDefaultLayers

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

示例14: loadServiceLayer

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsVectorLayer [as 别名]
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) 
开发者ID:dsgoficial,项目名称:DsgTools,代码行数:11,代码来源:bdgexGuiManager.py

示例15: getLayers

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


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