Coding 101
- Read the page "What is Python? lightly.
layer = qgis.utils.iface.activeLayer()
layer.id()
layer.featureCount()
layer.source()
layer.wkbType()
layer.extent()
layer.srs()
layer.setTransparency(50)
Example
Following is revision of Tip: Count Number of Vertices in a Layer using QGIS based on info gleaned from QgsFeatureRequest replaces select()
layer = qgis.utils.iface.activeLayer()
provider = layer.dataProvider()
#provider.select()
#feat = QgsFeature()
vertex_count = 0
#while provider.nextFeatureID(feat):
for feat in provider.getFeatures():
geom = feat.geometry()
if geom.type() == QGis.Polygon:
layer_vertices = 0
if geom.isMultipart():
polygons = geom.asMultiPolygon()
else:
polygons = [ geom.asPolygon() ]
for polygon in polygons:
for ring in polygon:
layer_vertices += len(ring)
print "Feature %d: Vertices %d" % ( feat.id(), layer_vertices)
vertex_count += layer_vertices
print "Total vertices: %d" % (vertex_count)
Here's the (revised) code if we want to change the attribute table with this data
from PyQt4.QtCore import *
layer = qgis.utils.iface.activeLayer()
layer.startEditing()
layer.dataProvider().addAttributes( [ QgsField("Vertices", QVariant.Int) ] )
provider = layer.dataProvider()
vertices_field_index = provider.fieldNameIndex("Vertices")
# provider.select()
# feat = QgsFeature()
vertex_count = 0
attribute_dict = {}
# while provider.nextFeature(feat):
for feat in provider.getFeatures():
geom = feat.geometry()
if geom.type() == QGis.Polygon:
layer_vertices = 0
if geom.isMultipart():
polygons = geom.asMultiPolygon()
else:
polygons = [ geom.asPolygon() ]
for polygon in polygons:
for ring in polygon:
layer_vertices += len(ring)
print "Feature %d: Vertices %d" % ( feat.id(), layer_vertices)
vertex_count += layer_vertices
attribute_dict[feat.id()] = { vertices_field_index: QVariant(layer_vertices) }
print "Total vertices: %d" % (vertex_count)
layer.dataProvider().changeAttributeValues(attribute_dict)
layer.commitChanges()
Anita Graser QGIS Python Plugins – How to get started
Excellent Workshop on Python Tools and Plugins for QGIS
QGIS: Running Scripts in the Python Console
References, Resources, Glossaries
Wrappers, Bindings, and Ports
Introduction to the QGIS Python Cookbook
Developer Cookbook
Tutorial #2 – Exploring the QGIS Python Console