官术网_书友最值得收藏!

Adding a set of attributes to a vector layer

Each QGIS feature has two parts, the geometry and the attributes. In this recipe, we'll add an attribute for a layer from an existing dataset.

Getting ready

We will use a point shapefile with museum data for New York City, which you can download as a ZIP file from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.

Extract this shapefile to the /qgis_data/nyc directory.

How to do it...

A feature must have geometry, but it does not require attributes. So, we will create a new feature, add some attributes, and then add everything to the layer, as follows:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. First, load the layer and validate it:
    vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
    vectorLyr.isValid()
    
  4. Next, access the layer's data provider so that we can get the list of fields:
    vpr = vectorLyr.dataProvider()
    
  5. Now, create a point geometry, which in this case is a new museum:
    pnt = QgsGeometry.fromPoint(QgsPoint(-74.13401,40.62148))
    
  6. Next, get the fields object for the layer that we'll need to create a new feature for:
    fields = vpr.fields()
    
  7. Then, create a new feature and initialize the attributes:
    f = QgsFeature(fields)
    
  8. Now, set the geometry of our new museum feature:
    f.setGeometry(pnt)
    
  9. Now, we are able to add a new attribute. Adding an attribute is similar to updating a Python dictionary, as shown here:
    f['NAME'] = 'Python Museum'
    
  10. Finally, we add the feature to the layer and update the extents:
    vpr.addFeatures([f])
    vectorLyr.updateExtents()
    

How it works...

PyQGIS attributes are defined as an ordered array. The syntax for referencing a field is similar to the syntax for a Python dictionary. We use the layer's data provider object to perform the actual editing. When we use this approach, no signals are triggered at the layer object level. If we are just trying to edit data on the filesystem, that's okay, but if the layer is going to be added to the map canvas for display or user interaction, then you should use the editing buffer in the QgsVectorLayer object. This editing buffer allows you to commit or roll back changes and also keeps track of the state of the layer when things are changed.

主站蜘蛛池模板: 渝北区| 四子王旗| 中阳县| 嘉荫县| 宽甸| 洪江市| 曲阜市| 左云县| 苍山县| 永胜县| 南京市| 巍山| 光山县| 疏附县| 丽水市| 加查县| 七台河市| 芦山县| 唐山市| 鲁甸县| 平和县| 当雄县| 洛浦县| 兴城市| 襄城县| 英山县| 航空| 平定县| 山东| 抚宁县| 都匀市| 庆云县| 朝阳市| 牡丹江市| 新巴尔虎右旗| 金沙县| 柘荣县| 岫岩| 田林县| 巢湖市| 黄平县|