Logotipo de Qgis Core Architecture

Qgis Core Architecture

Organización
Impertio-Studio
qgis-core-architecture

Use when creating QGIS projects, understanding PyQGIS architecture, or reasoning about the QGIS data model. Prevents mixing standalone script initialization with plugin context, and threading violations. Covers Qt-based architecture, 5 core modules, project lifecycle, layer model, provider system, and QGIS 4.0 Qt6 notes. Keywords: QGIS architecture, QgsProject, QgsApplication, PyQGIS modules, layer model, provider system, plugin architecture, how QGIS works, QGIS internals, PyQGIS overview.

Descripción general

EditorImpertio-Studio
RepositorioQGIS-Claude-Skill-Package
Nombre de la habilidadqgis-core-architecture
Estrellas
39
Forks
2
Archivos incluidos
3
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Archivos incluidos: 3

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por Impertio-Studio en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Qgis Core Architecture en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package/tree/main/skills/source/qgis-core/qgis-core-architecture
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

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-core/qgis-core-architecture .claude/skills/qgis-core-architecture
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Qgis Core Architecture en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Qgis Core Architecture automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Qgis Core Architecture no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

qgis-core-architecture

Quick Reference

Core Python Modules (QGIS 3.x)

ModulePurpose
qgis.coreAll non-GUI functionality: layers, features, geometry, CRS, project, processing, data providers
qgis.guiGUI components: map canvas (QgsMapCanvas), layer tree view, attribute forms
qgis.analysisSpatial analysis: network analysis, raster calculator, interpolation
qgis.serverQGIS Server for OGC web services (WMS, WFS, WCS)
qgis._3d3D map visualization components

Additional utility modules:

  • qgis.utils -- Automatically imported in the QGIS Python console; provides helper functions
  • qgis.PyQt -- Re-exports PyQt5/PyQt6 classes for version-independent imports

Layer Type Hierarchy

ClassType EnumDescription
QgsVectorLayerVectorLayerPoints, lines, polygons with attributes
QgsRasterLayerRasterLayerGrid-based data (GeoTIFF, WMS, XYZ tiles)
QgsMeshLayerMeshLayerUnstructured mesh data (hydrodynamic models)
QgsPointCloudLayerPointCloudLayerLiDAR / point cloud data (LAS, LAZ, COPC, EPT)
QgsAnnotationLayerAnnotationLayerFreeform annotations on the map
QgsVectorTileLayerVectorTileLayerMapbox Vector Tiles (MVT)
QgsTiledSceneLayerTiledSceneLayer3D tiled scenes (3D Tiles, Cesium)

All layer types inherit from QgsMapLayer. Access the type via layer.type().

Project File Formats

FormatExtensionDescription
QGS.qgsXML-based project file; human-readable, larger file size
QGZ.qgzCompressed ZIP archive containing .qgs and auxiliary data; default since QGIS 3.2

Key Dependencies

ComponentRole
Qt5 / Qt6Application framework (Qt6 in QGIS 4.x)
SIPC++ to Python binding generator (tighter Qt integration than SWIG)
PyQt5 / PyQt6Python Qt bindings
GDAL/OGRRaster and vector data I/O
PROJCoordinate reference system transformations
GEOSGeometry operations

Critical Warnings

NEVER access QgsProject.instance() from background threads without proper synchronization. The project singleton is NOT thread-safe for writes.

NEVER modify GUI elements (map canvas, layer tree, dialogs) from background threads. ALWAYS use QgsTask and emit signals to communicate results back to the main thread.

NEVER create layers on a background thread and add them to the project directly. Create the data on the background thread, then add the layer on the main thread via signal.

NEVER assume a layer is valid without calling isValid(). A layer can be created without errors but still be invalid (wrong path, missing provider, auth failure).

NEVER access features or data provider methods on an invalid layer -- this leads to crashes or undefined behavior.

NEVER call QgsProject.instance().clear() without confirming that unsaved changes are acceptable -- this destroys all loaded layers and settings immediately.

NEVER rely on QgsProject.instance().mapLayersByName() returning a single result -- layer names are NOT unique. ALWAYS index into the returned list and handle empty lists.

NEVER use backslashes in paths even on Windows -- QGIS/Qt normalizes to forward slashes internally. Using backslashes in URIs causes provider failures.

NEVER call QgsApplication([], False) without first calling QgsApplication.setPrefixPath() -- providers will fail to load.

ALWAYS call qgs.exitQgis() at the end of standalone scripts to prevent memory leaks.

ALWAYS check layer validity immediately after creation with layer.isValid().


Decision Tree

Which Initialization Context?

Are you writing code inside the QGIS application?
├── YES (plugin or Python console)
│   └── QgsApplication is ALREADY initialized
│       ├── `iface` is available (QgisInterface)
│       ├── `QgsProject.instance()` is ready
│       └── Do NOT call QgsApplication() or initQgis()
├── NO (standalone script, no GUI)
│   └── MUST initialize QgsApplication manually:
│       1. QgsApplication.setPrefixPath(path, True)
│       2. qgs = QgsApplication([], False)
│       3. qgs.initQgis()
│       4. ... your code ...
│       5. qgs.exitQgis()
└── NO (standalone script, with GUI)
    └── Same as above but pass True to QgsApplication:
        1. QgsApplication.setPrefixPath(path, True)
        2. qgs = QgsApplication([], True)
        3. qgs.initQgis()
        4. ... your GUI code ...
        5. qgs.exitQgis()

Which Layer Class?

What kind of data are you loading?
├── Vector data (points, lines, polygons) → QgsVectorLayer
├── Raster/grid data (GeoTIFF, DEM) → QgsRasterLayer
├── Mesh data (hydrodynamic models) → QgsMeshLayer
├── Point cloud (LAS, LAZ, COPC) → QgsPointCloudLayer
├── Vector tiles (MVT) → QgsVectorTileLayer
├── 3D tiled scenes (Cesium 3D Tiles) → QgsTiledSceneLayer
└── Map annotations → QgsAnnotationLayer

Which Data Provider?

What is your data source?
├── Local vector file (.shp, .gpkg, .geojson, .fgb, .kml) → provider: "ogr"
├── Local raster file (.tif, .jp2, .vrt) → provider: "gdal"
├── PostgreSQL/PostGIS database → provider: "postgres"
├── SpatiaLite database → provider: "spatialite"
├── In-memory layer → provider: "memory"
├── Delimited text file (.csv with coordinates) → provider: "delimitedtext"
├── WFS web service → provider: "WFS"
├── WMS/WMTS web service → provider: "wms"
├── WCS web service → provider: "wcs"
├── GPX file → provider: "gpx"
└── Virtual layer (SQL over layers) → provider: "virtual"

Essential Patterns

Standalone Script Initialization (No GUI)

python
from qgis.core import QgsApplication, QgsVectorLayer, QgsProject

QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
qgs = QgsApplication([], False)
qgs.initQgis()

# Load and work with layers
layer = QgsVectorLayer("data/airports.gpkg|layername=airports", "Airports", "ogr")
if not layer.isValid():
    raise RuntimeError("Layer failed to load")

QgsProject.instance().addMapLayer(layer)

# ALWAYS clean up
qgs.exitQgis()

Plugin Entry Point Pattern

python
class MyPlugin:
    def __init__(self, iface):
        self.iface = iface  # QgisInterface instance

    def initGui(self):
        # Register actions, menus, toolbars
        self.action = QAction("My Plugin", self.iface.mainWindow())
        self.action.triggered.connect(self.run)
        self.iface.addToolBarIcon(self.action)

    def unload(self):
        # ALWAYS clean up all registered elements
        self.iface.removeToolBarIcon(self.action)

    def run(self):
        # Plugin logic here
        layer = self.iface.activeLayer()
        if layer is not None and layer.isValid():
            # Process layer
            pass

def classFactory(iface):
    return MyPlugin(iface)

Project Operations

python
project = QgsProject.instance()

# Load project
success = project.read("/path/to/project.qgz")

# Load project skipping layer resolution (fast, for metadata access)
readflags = Qgis.ProjectReadFlags()
readflags |= Qgis.ProjectReadFlag.DontResolveLayers
project.read("/path/to/project.qgs", readflags)

# Save project
project.write()                            # Save to current location
project.write("/path/to/new_project.qgz")  # Save to new path

# Access all layers (returns dict of {id: layer})
all_layers = project.mapLayers()

# Find layers by name (returns list -- names are NOT unique)
layers = project.mapLayersByName("Airports")
if not layers:
    raise RuntimeError("Layer 'Airports' not found")
layer = layers[0]

Layer Creation and Validation

python
# Vector layer
vlayer = QgsVectorLayer("data/airports.shp", "Airports", "ogr")
if not vlayer.isValid():
    raise RuntimeError(f"Failed to load layer: {vlayer.name()}")
QgsProject.instance().addMapLayer(vlayer)

# Raster layer
rlayer = QgsRasterLayer("data/srtm.tif", "SRTM", "gdal")
if not rlayer.isValid():
    raise RuntimeError(f"Failed to load raster: {rlayer.name()}")
QgsProject.instance().addMapLayer(rlayer)

# Memory layer (for temporary data)
mem_layer = QgsVectorLayer("Point?crs=EPSG:4326", "Temp Points", "memory")

Background Processing with QgsTask

python
from qgis.core import QgsTask, QgsApplication

class HeavyProcessingTask(QgsTask):
    def __init__(self, description, layer_id):
        super().__init__(description, QgsTask.CanCancel)
        self.layer_id = layer_id
        self.result_data = None

    def run(self):
        # Runs on background thread -- NO GUI access here
        # NO QgsProject.instance() writes here
        self.result_data = self._process_data()
        return True

    def finished(self, result):
        # Runs on main thread -- safe to update GUI and project
        if result:
            # Add results to project here
            pass

task = HeavyProcessingTask("Processing data", layer.id())
QgsApplication.taskManager().addTask(task)

Signal/Slot Connections

python
# Connect to project layer changes
QgsProject.instance().layersAdded.connect(on_layers_added)
QgsProject.instance().layersRemoved.connect(on_layers_removed)

# Connect to map canvas render
iface.mapCanvas().renderComplete.connect(on_render_complete)

# ALWAYS disconnect when done (e.g., in plugin unload)
QgsProject.instance().layersAdded.disconnect(on_layers_added)
iface.mapCanvas().renderComplete.disconnect(on_render_complete)

Common Operations

Path Resolution

python
# Rewrite paths during loading (e.g., migrating between machines)
def my_load_preprocessor(path):
    return path.replace("c:/Users/Old/", "x:/New/")

preprocessor_id = QgsPathResolver.setPathPreprocessor(my_load_preprocessor)

# Remove preprocessor when no longer needed
QgsPathResolver.removePathPreprocessor(preprocessor_id)

Layer Tree Management

python
root = QgsProject.instance().layerTreeRoot()

# Create a group
group = root.addGroup("Analysis Results")

# Add layer to specific group (not root)
QgsProject.instance().addMapLayer(layer, False)  # False = don't add to root
group.addLayer(layer)

# Find group or layer node
my_group = root.findGroup("Analysis Results")
node = root.findLayer(layer.id())

Canvas-Project Bridge (Standalone GUI Apps)

python
from qgis.core import QgsProject
from qgis.gui import QgsLayerTreeMapCanvasBridge

bridge = QgsLayerTreeMapCanvasBridge(
    QgsProject.instance().layerTreeRoot(),
    canvas
)
project.read("/path/to/project.qgs")

QGIS 4.0 Migration Notes (Qt6)

QMetaType.Type Replaces QVariant.Type

python
# QGIS 3.x (Qt5) -- WILL BREAK in QGIS 4.x
from qgis.PyQt.QtCore import QVariant
field = QgsField("name", QVariant.String)

# QGIS 4.x (Qt6) -- Forward-compatible
from qgis.PyQt.QtCore import QMetaType
field = QgsField("name", QMetaType.Type.QString)
Qt5 (QVariant.Type)Qt6 (QMetaType.Type)
QVariant.StringQMetaType.Type.QString
QVariant.IntQMetaType.Type.Int
QVariant.DoubleQMetaType.Type.Double
QVariant.BoolQMetaType.Type.Bool
QVariant.DateQMetaType.Type.QDate
QVariant.DateTimeQMetaType.Type.QDateTime
QVariant.LongLongQMetaType.Type.LongLong

Other Qt6 Breaking Changes

  • QRegExp removed -- use QRegularExpression instead
  • exec_() methods renamed to exec() (dialogs, event loops)
  • Enum scoping changes -- unscoped enums become scoped
  • Use qgis.PyQt imports to abstract differences between PyQt5 and PyQt6

Reference Links

Official Sources

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Son archivos de solo lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de IA Qgis Core Architecture?

Use when creating QGIS projects, understanding PyQGIS architecture, or reasoning about the QGIS data model. Prevents mixing standalone script initialization with plugin context, and threading violations. Covers Qt-based architecture, 5 core modules, project lifecycle, layer model, provider system, and QGIS 4.0 Qt6 notes. Keywords: QGIS architecture, QgsProject, QgsApplication, PyQGIS modules, layer model, provider system, plugin architecture, how QGIS works, QGIS internals, PyQGIS overview.

¿Por qué usar Qgis Core Architecture en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Qgis Core Architecture está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Qgis Core Architecture en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package/tree/main/skills/source/qgis-core/qgis-core-architecture. TypingMind lee el archivo SKILL.md de esa carpeta, empaqueta los archivos de la carpeta e instala el conjunto como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Qgis Core Architecture?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Qgis Core Architecture?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Qgis Core Architecture con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Qgis Core Architecture?

Sí. Impertio-Studio la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇