Pyqgis

From znlgis/opengis-skills · View interactive version

Pyqgis is an AI agent skill from the GitHub repository znlgis/opengis-skills. Use when scripting QGIS with Python — QgsApplication standalone init, QgsVectorLayer / QgsRasterLayer loading, processing.run after Processing.initialize(), QgsGeometry / QgsExpression, QgsMapSettings rendering and QgsLayoutExporter PDF/PNG export, qgis._3d, or debugging \"import qgis.core\" failure

How to use this skill

Skill file

项目地址: <https://github.com/qgis/QGIS>

开发者手册: <https://docs.qgis.org/4.2/en/docs/pyqgis_developer_cookbook/>

Python API 参考: <https://qgis.org/pyqgis/4.2/>

最新版本: QGIS 4.2.3(截至 2026-11,下载页);LTR 3.44.15

许可证: GPL-2.0+

概述

PyQGIS 是 QGIS 桌面 GIS 软件的 Python 绑定层,对应 QGIS 源码中 python/ 目录下的绑定代码。它将 QGIS 核心 C++ 类库完整暴露给 Python,使得开发者可以:

PyQGIS 主要包含以下模块:

| 模块 | 说明 |

|------|------|

| qgis.core | 核心类——图层、要素、几何、坐标系、项目、Processing 等 |

| qgis.gui | GUI 组件——地图画布、地图工具、符号选择器等 |

| qgis.analysis | 空间分析——插值、网络分析、栅格计算等 |

| processing | Processing 算法调用入口(独立 Python 模块,processing.run();非 qgis.processing) |

| qgis.server | QGIS Server Python 插件接口 |

| qgis._3d | 3D 地图视图相关类 |

| qgis.PyQt | PyQt5/PyQt6 兼容层 |


环境准备

前置条件

探测发行包实际使用的解释器版本(在任何 QGIS Python 环境里):

python -c "import sys; print(sys.version)"

在 QGIS Python 控制台中使用

打开 QGIS 桌面 → 菜单「Plugins → Python Console」,即可直接使用 PyQGIS:

# QGIS 控制台中无需初始化,直接使用
layer = iface.activeLayer()
print(layer.name(), layer.featureCount())

独立脚本(Standalone Script)

在 QGIS 外部运行 Python 脚本时,需要先初始化 QGIS 应用:

import sys
from qgis.core import QgsApplication

# 初始化 QGIS(False 表示不使用 GUI)
qgs = QgsApplication([], False)
qgs.setPrefixPath("/usr", True)  # Linux; Windows 示例:"C:/OSGeo4W/apps/qgis"
qgs.initQgis()

# ===== 在此处编写 PyQGIS 代码 =====

# 退出
qgs.exitQgis()

独立脚本中使用 Processing

import sys
from qgis.core import QgsApplication
import processing
from processing.core.Processing import Processing

qgs = QgsApplication([], False)
qgs.setPrefixPath("/usr", True)
qgs.initQgis()

# 初始化 Processing 框架
Processing.initialize()

# 现在可以使用 processing.run()
result = processing.run("native:buffer", {
    'INPUT': '/data/points.shp',
    'DISTANCE': 100,
    'OUTPUT': '/data/buffered.shp'
})

qgs.exitQgis()

Headless 服务器环境

export QT_QPA_PLATFORM=offscreen
python3 my_pyqgis_script.py

核心 API 一览

项目与应用

| 类 | 模块 | 用途 |

|---|---|---|

| QgsApplication | qgis.core | QGIS 应用实例,初始化/退出 |

| QgsProject | qgis.core | 项目管理(单例),加载/保存项目、管理图层 |

矢量图层与要素

| 类 | 模块 | 用途 |

|---|---|---|

| QgsVectorLayer | qgis.core | 矢量图层(Shapefile、GeoJSON、PostGIS、内存等) |

| QgsFeature | qgis.core | 单个要素(几何 + 属性) |

| QgsField / QgsFields | qgis.core | 属性字段定义与集合 |

| QgsFeatureRequest | qgis.core | 要素查询过滤器(空间/属性条件) |

| QgsVectorFileWriter | qgis.core | 矢量数据写出(SHP、GPKG、GeoJSON 等) |

| QgsVectorLayerUtils | qgis.core | 矢量图层工具方法集 |

| QgsSpatialIndex | qgis.core | 空间索引,加速空间查询 |

栅格图层

| 类 | 模块 | 用途 |

|---|---|---|

| QgsRasterLayer | qgis.core | 栅格图层(GeoTIFF、VRT、WMS 等) |

| QgsRasterPipe | qgis.core | 栅格渲染管线 |

| QgsRasterFileWriter | qgis.core | 栅格数据写出 |

几何

| 类 | 模块 | 用途 |

|---|---|---|

| QgsGeometry | qgis.core | 几何对象封装(含空间操作方法) |

| QgsPointXY | qgis.core | 二维点坐标 |

| QgsPoint | qgis.core | 三维点坐标(含 Z / M) |

| QgsRectangle | qgis.core | 矩形范围(Bounding Box) |

| QgsWkbTypes | qgis.core | WKB 几何类型枚举 |

| QgsDistanceArea | qgis.core | 距离和面积计算(支持椭球面) |

坐标参考系与变换

| 类 | 模块 | 用途 |

|---|---|---|

| QgsCoordinateReferenceSystem | qgis.core | 坐标参考系(CRS)对象 |

| QgsCoordinateTransform | qgis.core | 坐标变换器 |

| QgsCoordinateTransformContext | qgis.core | 坐标变换上下文 |

表达式

| 类 | 模块 | 用途 |

|---|---|---|

| QgsExpression | qgis.core | QGIS 表达式解析与求值 |

| QgsExpressionContext | qgis.core | 表达式计算上下文 |

| QgsExpressionContextUtils | qgis.core | 创建预设表达式上下文的工具方法 |

Processing 框架

| 类 | 模块 | 用途 |

|---|---|---|

| processing.run() | processing(QGIS 插件目录模块) | 执行 Processing 算法的核心入口 |

| QgsProcessingFeedback | qgis.core | 算法执行反馈(进度、日志) |

| QgsProcessingContext | qgis.core | 算法执行上下文 |

| QgsProcessingAlgorithm | qgis.core | 自定义算法基类 |

| QgsProcessingParameterDefinition | qgis.core | 算法参数定义基类 |

地图渲染

| 类 | 模块 | 用途 |

|---|---|---|

| QgsMapSettings | qgis.core | 地图渲染设置(范围、CRS、图层、尺寸) |

| QgsMapRendererSequentialJob | qgis.core | 顺序渲染任务 |

| QgsMapRendererParallelJob | qgis.core | 并行渲染任务 |

| QgsLayoutExporter | qgis.core | 打印布局导出(PDF、PNG、SVG) |

| QgsPrintLayout | qgis.core | 打印布局对象 |

数据提供者

| Provider 名称 | 说明 | 示例 URI |

|---|---|---|

| ogr | OGR 矢量(SHP、GeoJSON、GPKG、FileGDB 等) | /path/to/file.shp |

| gdal | GDAL 栅格(GeoTIFF、VRT、ECW 等) | /path/to/dem.tif |

| postgres | PostgreSQL / PostGIS | dbname='gis' host=localhost port=5432 table="public"."layer" (geom) |

| memory | 内存图层 | Point?crs=epsg:4326&field=id:integer&field=name:string(50) |

| wms | WMS / WMTS 服务 | url=https://example.com/wms&layers=dem&crs=EPSG:4326 |

| wfs | WFS 服务 | url=https://example.com/wfs&typename=buildings |

| delimitedtext | CSV / 分隔文本 | file:///path/to/data.csv?delimiter=,&xField=lon&yField=lat&crs=epsg:4326 |

| spatialite | SpatiaLite 数据库 | dbname='/path/to/db.sqlite' table="layer" (geometry) |

| virtual | 虚拟图层(SQL 查询) | SQL 表达式 |


项目管理

加载与保存项目

from qgis.core import QgsProject

project = QgsProject.instance()

# 读取项目
project.read("/path/to/project.qgs")

# 获取所有图层
layers = project.mapLayers()  # 返回 dict {layer_id: layer}

# 保存项目
project.write("/path/to/output.qgs")

添加/移除图层

from qgis.core import QgsProject, QgsVectorLayer

project = QgsProject.instance()

layer = QgsVectorLayer("/data/roads.shp", "roads", "ogr")
if layer.isValid():
    project.addMapLayer(layer)

# 移除图层
project.removeMapLayer(layer.id())

矢量图层与栅格图层操作的完整 API 与示例见 reference/vector-raster-layers.md

坐标参考系与变换

创建 CRS

from qgis.core import QgsCoordinateReferenceSystem

# 从 EPSG 代码
crs = QgsCoordinateReferenceSystem("EPSG:4326")

# 从 WKT
crs = QgsCoordinateReferenceSystem.fromWkt(wkt_string)

# 从 Proj 字符串
crs = QgsCoordinateReferenceSystem.fromProj4(proj4_string)

# 获取图层 CRS
crs = layer.crs()
print(crs.authid())       # "EPSG:4326"
print(crs.description())  # "WGS 84"

坐标变换

from qgis.core import QgsCoordinateTransform, QgsCoordinateReferenceSystem, QgsProject

src_crs = QgsCoordinateReferenceSystem("EPSG:4326")
dst_crs = QgsCoordinateReferenceSystem("EPSG:3857")

transform = QgsCoordinateTransform(src_crs, dst_crs, QgsProject.instance())

# 变换单个点
point = transform.transform(QgsPointXY(116.4, 39.9))

# 变换几何
geom.transform(transform)

# 反向变换
point_back = transform.transform(point, QgsCoordinateTransform.ReverseTransform)

表达式

基本表达式求值

from qgis.core import QgsExpression, QgsExpressionContext, QgsExpressionContextUtils

# 简单计算
exp = QgsExpression("1 + 2 * 3")
result = exp.evaluate()  # 7

# 基于要素的表达式
exp = QgsExpression('"population" / "area"')
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))

for feature in layer.getFeatures():
    context.setFeature(feature)
    value = exp.evaluate(context)
    print(feature["name"], value)

过滤要素

# 表达式过滤
exp = QgsExpression('"type" = \'residential\' AND "area" > 1000')
request = QgsFeatureRequest(exp)

for feature in layer.getFeatures(request):
    print(feature.attributes())

字段计算器

from qgis.core import QgsExpression

layer.startEditing()

# 使用表达式批量更新字段
expression = QgsExpression('"length" * "width"')
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))

field_index = layer.fields().indexOf("area")
for feature in layer.getFeatures():
    context.setFeature(feature)
    value = expression.evaluate(context)
    layer.changeAttributeValue(feature.id(), field_index, value)

layer.commitChanges()

Processing 算法调用、地图渲染与导出、典型工作流示例见 reference/processing-rendering.md

典型工作流:缓冲区分析并导出

独立脚本端到端示例(加载 → 缓冲区 → 导出 GeoJSON):

from qgis.core import QgsApplication, QgsVectorLayer
import processing
from processing.core.Processing import Processing

# 初始化(独立脚本必需)
qgs = QgsApplication([], False)
qgs.setPrefixPath("/usr", True)   # Windows 示例:"C:/OSGeo4W/apps/qgis"
qgs.initQgis()
Processing.initialize()

# 加载数据
layer = QgsVectorLayer("/data/buildings.shp", "buildings", "ogr")
assert layer.isValid(), "图层加载失败"

# 缓冲区分析(100 米,输出 GeoJSON)
result = processing.run("native:buffer", {
    'INPUT': layer,
    'DISTANCE': 100,
    'OUTPUT': '/data/buildings_buffer.geojson'
})
print(result['OUTPUT'])

qgs.exitQgis()

更多工作流(批量缓冲融合、栅格裁剪、打印布局导出)见 reference/processing-rendering.md。

常见问题

| 问题 | 解决 |

|------|------|

| 独立脚本 import qgis.core 失败 | 使用 QGIS 自带 Python 解释器(Windows 位于 apps/Python312),或配置 PYTHONPATH 指向 QGIS 的 python 目录 |

| 图层 isValid() 为 false | 检查文件路径与 provider 拼写(ogr / gdal / postgres),打印 layer.error().message() 定位原因 |

| processing.run() 报算法不存在 | 独立脚本先调用 Processing.initialize();第三方算法需在 QGIS 中启用对应插件 |

| 无显示环境运行崩溃 | 服务器/CI 设置 QT_QPA_PLATFORM=offscreen |

| 渲染输出空白 | 检查 QgsMapSettings 的 extent / CRS / 输出尺寸与图层有效性 |

| 距离/面积结果偏大或偏小 | 经纬度数据用 QgsDistanceArea 并设置椭球;或先投影到米制坐标系 |

| 表达式字段引用报错 | 字段名用双引号 "field",字符串值用单引号 'value' |

| 中文属性乱码 | 指定数据源编码(如 CSV ?encoding=UTF-8);QGIS 4.x 默认 UTF-8 |


AI 使用建议


相关技能

参考资源

注意: docs.qgis.org/4.2/... 目前会 302 跳到 /testing/,4.2 的 cookbook 与用户手册尚未定稿;查阅 4.2 类与方法签名以 <https://qgis.org/pyqgis/4.2/> 为准。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.