python qgis 创建要素类
时间: 2024-01-11 09:19:11 浏览: 179
QGIS310的Python脚本-坐标点转面.zip
要在QGIS中使用Python创建要素类,可以使用QGIS Python API中的QgsVectorLayer类。以下是创建要素类的步骤:
1. 导入必要的模块和类:
```python
from qgis.core import QgsVectorLayer, QgsField, QgsFeature, QgsGeometry, QgsPointXY
from PyQt5.QtCore import QVariant
```
2. 定义要素类的字段:
```python
fields = QgsFields()
fields.append(QgsField('id', QVariant.Int))
fields.append(QgsField('name', QVariant.String))
```
3. 创建要素类:
```python
crs = QgsCoordinateReferenceSystem('EPSG:4326') # 定义坐标系
layer = QgsVectorLayer('Point?crs='+ crs.toWkt(), 'layer_name', 'memory') # 创建点要素类
layer.startEditing()
layer.dataProvider().addAttributes(fields)
layer.updateFields()
```
4. 添加要素:
```python
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(0, 0))) # 设置要素的几何形状
feature.setAttributes([1, 'feature_name']) # 设置要素的属性值
layer.addFeature(feature)
```
5. 保存要素类:
```python
layer.commitChanges()
```
阅读全文