QGIS + Python Part 2

Execution operation check environment

Addition of fields (columns / columns) in the attribute table

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 ()

Set the attributes of features

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')

Get features that match specific attribute conditions using "expressions"

――The "expression" here is an expression described in the expression builder (↓↓). - Image2.png

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.

Expression description rules

--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.

Select features that match specific attribute conditions

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 )

Get the layer entity from the layer name

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))

Related posts

-Python + GIS Part 1

Reference material

-Introduction to QGIS Programming 2016 Osaka Edition

Recommended Posts

QGIS + Python Part 2
QGIS + Python Part 1
Python: Scraping Part 1
Python3 Beginning Part 1
Python: Scraping Part 2
Python basic memorandum part 2
Python basic memo --Part 2
Python basic memo --Part 1
Image processing with Python (Part 2)
Studying Python with freeCodeCamp part1
Bordering images with python Part 1
Python application: Pandas Part 1: Basic
Python application: Pandas Part 2: Series
Scraping with Selenium + Python Part 1
Python: Ship Survival Prediction Part 2
Python
Python: Supervised Learning: Hyperparameters Part 1
Python Basic Grammar Memo (Part 1)
Python: Ship Survival Prediction Part 1
Studying Python with freeCodeCamp part2
Image processing with Python (Part 1)
Solving Sudoku with Python (Part 2)
Image processing with Python (Part 3)
Python: Ship Survival Prediction Part 3
Python: Stock Price Forecast Part 2
UI Automation Part 2 in Python
Python: Supervised Learning: Hyperparameters Part 2
Scraping with Selenium + Python Part 2
Basics of Python × GIS (Part 1)
Python: Stock Price Forecast Part 1
Transpose CSV files in Python Part 1
Basics of Python x GIS (Part 3)
Playing handwritten numbers with python Part 1
perl objects and python class part 2.
Python Application: Data Cleansing Part 1: Python Notation
[Automation with python! ] Part 1: Setting file
Python Application: Data Handling Part 3: Data Format
Introduction to Python Hands On Part 1
Studying Python Part.1 Creating an environment
[Blender x Python] Particle Animation (Part 1)
Python application: Numpy Part 3: Double array
Basics of Python x GIS (Part 2)
perl objects and python class part 1.
Automate simple tasks with Python Part0
Python application: data visualization part 1: basic
[Automation with python! ] Part 2: File operation
Excel aggregation with Python pandas Part 1
kafka python
datetime part 1
Basic Linear Algebra Learned in Python (Part 1)
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Homebrew Python Part 3-Amazon Product Search Program
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster