打开QGIS Desktop 3.22.16,加载一个矢量图(Ex48/area.shp)
激活当前矢量图层
layer=iface.activeLayer()
获取当前矢量图层矢量数据的个数
from qgis.utils import iface
layer = iface.activeLayer() # 得到当前激活的图层
print(layer.id())
print(layer.featureCount()) # 返回矢量图层特征的数量
访问图层中的某一个要素
layer = iface.activeLayer()
for feat in layer.getFeatures():
geom=feat.geometry()
print(type(geom))
print(geom.asWkt()[:10],geom.area(),geom.length())
通过id访问要素
print('the layer has {} features.'.format(layer.featureCount()))
feat = layer.getFeature(10) # id < featureCount
print(feat.id())
print(feat.isValid()) # return true
检查id是否有效:id要小于要素个数
得到要素的属性信息
attr = feat1.attributes()
提取多边形节点
vertices = list(geom.vertices())
显示节点
def getgtypes():
return 'point', 'linestring', 'polygon', 'multipoint', 'multilinestring', 'multipolygon'
def showgeoms(geoms, name="tmp", gtype=None):
# 快速显示一串几何对象,gtype 如果是默认的则根据geoms生成相应的类型
if gtype is None:
gtype = geoms[0].constGet().geometryType() if isinstance(geoms[0], QgsGeometry) else geoms[0].geometryType()
gtype = gtype.lower()
if gtype not in getgtypes():
raise Exception('gtype should be one of :{' + ','.join(getgtypes()) + '}' + 'input gtype is {}'.format(gtype))
vl = QgsVectorLayer(gtype, name, "memory")
pr = vl.dataProvider()
feats = []
for geom in geoms:
feat = QgsFeature()
feat.setGeometry(geom)
feats.append(feat)
pr.addFeatures(feats)
QgsProject.instance().addMapLayer(vl)
iface.zoomFull()
layer = iface.activeLayer()
feat = layer.getFeature(12)
geom = feat.geometry()
vertices = list(geom.vertices())
showgeoms(vertices, 'feat12')
上面的代码运行时没有效果。。。
参考:矢量图层中要素的几何特征和属性特征的访问