test.py
# -*- coding: utf-8 -*-
from PyQt4.QtCore import QVariant
layer=iface.activeLayer()
if layer is None :
print(u'There is no active layer.')
layer.startEditing()
layer.dataProvider().addAttributes( [
QgsField('TestString', QVariant.String),
QgsField('TestInt', QVariant.Int),
QgsField('TestDouble', QVariant.Double)
] )
layer.updateFields()
layer.commitChanges()
--from PyQt4.QtCore import QVariant
is required for QVariant.String
--Work without layer.startEditing ()
TestString_1
.test.py
# -*- coding: utf-8 -*-
from PyQt4.QtCore import QVariant
layer=iface.activeLayer()
if layer is None :
print(u'There is no active layer.')
attributeName='TestString'
layer.startEditing()
for feature in layer.getFeatures():
feature[attributeName]='ABC'
layer.updateFeature(feature)
layer.commitChanges()
--In the above, set the TestString field value of all features on the layer to ABC (overwrite)
--Instead of feature [attributeName] ='ABC'
, you can usefeature.setAttribute (attributeName,'ABC')
――The "expression" here is an expression described in the expression builder (↓↓). -
test.py
# -*- coding: utf-8 -*-
layer=iface.activeLayer()
if layer is None :
print(u'There is no active layer.')
req = QgsFeatureRequest().setFilterExpression( u'"id" = \'A14_000_1234\'' )
features = layer.getFeatures( req )
attributeName='TestString'
layer.startEditing()
for feature in features:
feature.setAttribute(attributeName, 'XYZ')
layer.updateFeature(feature)
layer.commitChanges()
--The above is an example of getting a feature that matches the ʻid field value of ʻA14_000_1234
.
--The ** name ** of the field (column / column / attribute) is described in double quotation marks. --The ** value (character string) ** of the field is described in single quotation marks. --However, if the value of the field is a numerical value, describe it as it is.
test.py
# -*- coding: utf-8 -*-
layer=iface.activeLayer()
if layer is None :
print(u'There is no active layer.')
req = QgsFeatureRequest().setFilterExpression( u'"TestInt" > 2000' )
features = layer.getFeatures( req )
layer.setSelectedFeatures([featur.id() for featur in features])
--In the argument of setSelectedFeatures ()
, set the ** id list ** of the feature instead of the entity (instance) list of the feature.
- void QgsVectorLayer::setSelectedFeatures ( const QgsFeatureIds & ids )
test.py
# -*- coding: utf-8 -*-
layerName = 'test lay01 Polygon'
layer = None
for layer_ in QgsMapLayerRegistry.instance().mapLayers().values():
if layer_.name() == layerName:
layer = layer_
break
if layer is None :
print(u'layer"{0}"Does not exist.'.format(layerName))
-Introduction to QGIS Programming 2016 Osaka Edition
Recommended Posts