Logo Qgis Syntax Pyqgis Api

Qgis Syntax Pyqgis Api

Tổ chức
Impertio-Studio
qgis-syntax-pyqgis-api

Use when writing PyQGIS scripts, accessing features, editing layers, or performing geometry operations. Prevents edit session violations, threading crashes, and inefficient feature iteration. Covers 4 scripting contexts, feature CRUD, geometry operations, spatial indexing, background tasks, and basic symbology. Keywords: PyQGIS, QgsFeature, QgsFeatureRequest, QgsGeometry, edit layer, spatial index, QgsTask, background thread, symbology, read features, loop through layer, change style, select by attribute.

Tổng quan

Nhà phát hànhImpertio-Studio
Kho mãQGIS-Claude-Skill-Package
Tên kỹ năngqgis-syntax-pyqgis-api
Sao
39
Bản fork
2
Tệp đi kèm
3
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 3 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được Impertio-Studio công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Qgis Syntax Pyqgis Api trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package/tree/main/skills/source/qgis-syntax/qgis-syntax-pyqgis-api
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package.git /tmp/QGIS-Claude-Skill-Package
mkdir -p .claude/skills
cp -r /tmp/QGIS-Claude-Skill-Package/skills/source/qgis-syntax/qgis-syntax-pyqgis-api .claude/skills/qgis-syntax-pyqgis-api
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Qgis Syntax Pyqgis Api trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Qgis Syntax Pyqgis Api ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Qgis Syntax Pyqgis Api với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

qgis-syntax-pyqgis-api

Quick Reference

Scripting Contexts

Contextiface AvailableInitialization RequiredUse Case
Python ConsoleYesNoneInteractive exploration, quick tests
Standalone ScriptNoQgsApplication([], False) + initQgis()CLI tools, CI pipelines, batch processing
Processing ScriptNo (feedback instead)None (framework handles it)Geoprocessing algorithms
PluginYes (via classFactory)NoneGUI extensions, toolbar tools

Core Classes

ClassPurposeKey Methods
QgsFeatureSingle feature (geometry + attributes)id(), geometry(), attributes(), __getitem__()
QgsFeatureRequestFilter/optimize feature queriessetFilterExpression(), setFilterRect(), setLimit(), setFlags()
QgsGeometryGeometry wrapper with GEOS operationsfromPointXY(), buffer(), intersection(), contains()
QgsSpatialIndexR-tree spatial indexaddFeature(), nearestNeighbor(), intersects()
QgsTaskBackground processingrun(), finished(), setProgress(), isCanceled()
QgsMessageLogLog panel messageslogMessage(msg, tag, level)
QgsMessageBarMap canvas notificationspushMessage(title, text, level, duration)

QgsPoint vs QgsPointXY

ClassDimensionsUse With
QgsPointXY2D (X, Y) onlyfromPointXY(), fromPolylineXY(), fromPolygonXY()
QgsPoint2D + Z + MfromPolyline(), 3D operations

ALWAYS use QgsPointXY for 2D operations. Use QgsPoint ONLY when Z or M values are required.


Critical Warnings

NEVER modify features outside an edit session. Changes are silently lost or corrupt the data source. ALWAYS use with edit(layer): or manually call startEditing() / commitChanges().

NEVER access iface, QgsProject.instance(), or any Qt widget from QgsTask.run(). These are main-thread objects. Accessing them from a background thread crashes QGIS.

NEVER raise exceptions in QgsTask.run(). ALWAYS catch exceptions internally and return False on failure.

NEVER use layer.featureCount() to check if features exist. Some providers return -1. ALWAYS use getFeatures() with setLimit(1) instead.

NEVER use print() in multithreaded code (expression functions, renderers, processing algorithms). ALWAYS use QgsMessageLog instead.

ALWAYS check for NULL geometries before operations: if not geom.isNull():.

ALWAYS use QgsDistanceArea for measurements on geographic (lat/lon) CRS. The simple area() and length() methods return values in layer units without CRS correction.

ALWAYS call layer.updateFields() after adding or removing fields via the data provider.

ALWAYS keep QgsProcessingContext and QgsProcessingFeedback alive for the duration of QgsProcessingAlgRunnerTask. Garbage collection crashes QGIS.


Decision Tree: Scripting Context

Need to write PyQGIS code?
|
+-- Running inside QGIS GUI?
|   |
|   +-- Quick test or exploration? --> Python Console (iface available)
|   +-- Reusable geoprocessing? --> Processing Script (QgsProcessingAlgorithm)
|   +-- GUI extension with toolbar? --> Plugin (classFactory + initGui/unload)
|
+-- Running outside QGIS?
    --> Standalone Script (QgsApplication init required)

Decision Tree: Feature Editing

Need to modify layer data?
|
+-- Bulk import / batch processing, no undo needed?
|   --> Data Provider direct: layer.dataProvider().addFeatures([...])
|
+-- Interactive editing, undo/redo needed?
|   --> Edit Buffer: with edit(layer): layer.addFeature(feat)
|
+-- Multiple edits as single undo operation?
    --> Edit Commands: layer.beginEditCommand("description")

Decision Tree: Spatial Queries

Need to find features by location?
|
+-- Single query against a layer?
|   --> QgsFeatureRequest().setFilterRect(extent)
|
+-- Repeated queries against same dataset?
|   |
|   +-- Point data only?
|   |   --> QgsSpatialIndexKDBush (fastest, static)
|   |
|   +-- Mixed geometry types?
|       --> QgsSpatialIndex (R-tree, dynamic)

Essential Patterns

Standalone Script Initialization

python
from qgis.core import QgsApplication, QgsVectorLayer

qgs = QgsApplication([], False)
qgs.initQgis()

# ... PyQGIS work here ...

qgs.exitQgis()  # ALWAYS clean up

Dual-Context Script (Console + Standalone)

python
try:
    from qgis.utils import iface
    layer = iface.activeLayer()
except ImportError:
    from qgis.core import QgsApplication
    qgs = QgsApplication([], False)
    qgs.initQgis()

Feature Iteration with Optimization

python
from qgis.core import QgsFeatureRequest

# Attributes only (skip geometry loading)
request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry)
request.setSubsetOfAttributes(['name', 'population'], layer.fields())

for feature in layer.getFeatures(request):
    print(feature['name'], feature['population'])

Feature Editing with Context Manager

python
from qgis.core import QgsFeature, QgsGeometry, QgsPointXY, edit

with edit(layer):
    feat = QgsFeature(layer.fields())
    feat.setAttributes([1, 'New Point'])
    feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(10.0, 52.0)))
    layer.addFeature(feat)
# commitChanges() called automatically; rollBack() on exception

Geometry Construction and Operations

python
from qgis.core import QgsGeometry, QgsPointXY

# Create geometries
point = QgsGeometry.fromPointXY(QgsPointXY(1.0, 2.0))
polygon = QgsGeometry.fromPolygonXY([[
    QgsPointXY(0, 0), QgsPointXY(2, 0),
    QgsPointXY(2, 2), QgsPointXY(0, 2), QgsPointXY(0, 0)
]])

# Predicates
if polygon.contains(point):
    print("Point is inside polygon")

# Operations
buffered = point.buffer(10.0, 5)
intersection = polygon.intersection(buffered)

Spatial Index Usage

python
from qgis.core import QgsSpatialIndex, QgsPointXY, QgsFeatureRequest

# Build index (bulk load is fastest)
index = QgsSpatialIndex(layer.getFeatures())

# Query nearest 5 features
nearest_ids = index.nearestNeighbor(QgsPointXY(25.4, 12.7), 5)

# Fetch actual features by ID
for fid in nearest_ids:
    feature = next(layer.getFeatures(QgsFeatureRequest().setFilterFid(fid)))

Background Task (QgsTask Subclass)

python
from qgis.core import QgsTask, QgsApplication, QgsMessageLog, Qgis

class ProcessingTask(QgsTask):
    def __init__(self, description, data):
        super().__init__(description, QgsTask.CanCancel)
        self.data = data  # Copy data BEFORE task starts
        self.result = None
        self.exception = None

    def run(self):
        """Background thread. NEVER access iface or QgsProject here."""
        try:
            for i, item in enumerate(self.data):
                if self.isCanceled():
                    return False
                self.result = process(item)
                self.setProgress((i + 1) / len(self.data) * 100)
            return True
        except Exception as e:
            self.exception = e
            return False

    def finished(self, result):
        """Main thread. Safe for GUI updates."""
        if result:
            QgsMessageLog.logMessage("Done", 'MyPlugin', Qgis.Success)
        elif self.exception:
            QgsMessageLog.logMessage(str(self.exception), 'MyPlugin', Qgis.Critical)

task = ProcessingTask("Heavy work", data_copy)
QgsApplication.taskManager().addTask(task)

User Communication

python
from qgis.core import QgsMessageLog, Qgis

# Log panel (always available, including background threads)
QgsMessageLog.logMessage("Info message", 'MyPlugin', Qgis.Info)
QgsMessageLog.logMessage("Warning", 'MyPlugin', Qgis.Warning)
QgsMessageLog.logMessage("Error", 'MyPlugin', Qgis.Critical)

# Message bar (main thread + iface only)
iface.messageBar().pushMessage("Title", "Text", level=Qgis.Success, duration=3)

Common Operations

Check If Layer Has Features

python
request = QgsFeatureRequest().setLimit(1)
has_features = bool(list(layer.getFeatures(request)))

Get Single Feature by ID

python
feature = next(layer.getFeatures(QgsFeatureRequest().setFilterFid(42)))

Add Fields to Layer

python
from qgis.PyQt.QtCore import QMetaType
from qgis.core import QgsField

layer.dataProvider().addAttributes([
    QgsField("name", QMetaType.Type.QString),
    QgsField("value", QMetaType.Type.Double),
])
layer.updateFields()  # ALWAYS call after field changes

Ellipsoid-Accurate Measurements

python
from qgis.core import QgsDistanceArea, QgsUnitTypes

d = QgsDistanceArea()
d.setEllipsoid('WGS84')

area_m2 = d.measureArea(geom)
area_km2 = d.convertAreaMeasurement(area_m2, QgsUnitTypes.AreaSquareKilometers)

Coordinate Transformation

python
from qgis.core import QgsCoordinateTransform, QgsCoordinateReferenceSystem, QgsProject

transform = QgsCoordinateTransform(
    QgsCoordinateReferenceSystem("EPSG:4326"),
    QgsCoordinateReferenceSystem("EPSG:3857"),
    QgsProject.instance()
)
geom.transform(transform)  # In-place transformation

Basic Symbology

python
from qgis.core import QgsMarkerSymbol

symbol = QgsMarkerSymbol.createSimple({'name': 'circle', 'color': 'red', 'size': '3'})
layer.renderer().setSymbol(symbol)
layer.triggerRepaint()

Renderer Types Overview

RendererClassUse Case
Single SymbolQgsSingleSymbolRendererAll features same style
CategorizedQgsCategorizedSymbolRendererDiscrete attribute values
GraduatedQgsGraduatedSymbolRendererNumeric ranges
Rule-BasedQgsRuleBasedRendererExpression-driven rules

Data Provider vs Edit Buffer

AspectData ProviderEdit Buffer
Methodlayer.dataProvider().addFeatures()layer.addFeature()
Undo supportNoYes
Edit session requiredNoYes
PerformanceFaster for bulk operationsSlower, safer
Use caseBatch processing, scriptsInteractive editing

Reference Links

Official Sources

Tệp đi kèm

Khi kỹ năng đã được tải, mô hình có thể đọc các tệp này nếu cần. Các tệp này chỉ dùng để đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Qgis Syntax Pyqgis Api làm được gì?

Use when writing PyQGIS scripts, accessing features, editing layers, or performing geometry operations. Prevents edit session violations, threading crashes, and inefficient feature iteration. Covers 4 scripting contexts, feature CRUD, geometry operations, spatial indexing, background tasks, and basic symbology. Keywords: PyQGIS, QgsFeature, QgsFeatureRequest, QgsGeometry, edit layer, spatial index, QgsTask, background thread, symbology, read features, loop through layer, change style, select by attribute.

Vì sao nên dùng Qgis Syntax Pyqgis Api trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Qgis Syntax Pyqgis Api là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Qgis Syntax Pyqgis Api trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package/tree/main/skills/source/qgis-syntax/qgis-syntax-pyqgis-api. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm rồi cài đặt cả gói dưới dạng một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Qgis Syntax Pyqgis Api?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Qgis Syntax Pyqgis Api với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Qgis Syntax Pyqgis Api với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Qgis Syntax Pyqgis Api có miễn phí không?

Có. Kỹ năng này được Impertio-Studio phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇