Importante

Translation is a community effort you can join. This page is currently translated at 55.64%.

2. Writing Guidelines

In general, when creating reST documentation for the QGIS project, please follow the Python documentation style guidelines. For convenience, we provide a set of general rules we rely on for writing QGIS documentation below.

2.1. Writing Documentation

2.1.1. Headlines

To each webpage of the documentation corresponds a .rst file.

Sections used to structure the text are identified through their title which is underlined (and overlined for the first level). Same level titles must use same character for underline adornment. In QGIS Documentation, you should use following styles for chapter, section, subsection and minisec.

********
Chapter
********

Section
=======

Subsection
----------

Minisec
.......

Subminisec
^^^^^^^^^^

2.1.2. Lists

Lists are useful for structuring the text. Here are some simple rules common to all lists:

  • Start all list items with a capital letter

  • Do not use punctuation after list items that only contain a single simple sentence

  • Use period ( . ) as punctuation for list items that consist of several sentences or a single compound sentence

2.1.3. Indentation

Indentation in ReStructuredText should be aligned with the list or markup marker. It is also possible to create block quotes with indentation. See the Specification

#. In a numbered list, there should be
   three spaces when you break lines
#. And next items directly follow

   * Nested lists
   * Are also possible
   * And when they also have
     a line that is too long,
     the text should be naturally
     aligned
   * and be in their own paragraph

However, if there is an unindented paragraph, this will reset the numbering:

#. This item starts at 1 again

2.1.4. Inline Tags

You can use tags to emphasize items.

  • Menu GUI: to mark a complete sequence of menu selections, including selecting submenus and choosing a specific operation, or any subsequence of such a sequence.

    :menuselection:`menu --> submenu`
    
  • Dialogs and Tab titles: Labels presented as part of an interactive user interface including window titles, tab titles, button and option labels.

    :guilabel:`title`
    
  • Filenames and directories

    :file:`README.rst`
    
  • Icons with popup text

    |icon| :sup:`popup_text`
    

    (see image below).

  • Keyboard shortcuts

    :kbd:`Ctrl+B`
    

    will show Ctrl+B

    When describing keyboard shortcuts, the following conventions should be used:

    • Letter keys are displayed using uppercase: S

    • Special keys are displayed with an uppercase first letter: Esc

    • Key combinations are displayed with a + sign between keys, without spaces: Shift+R

  • User text

    ``label``
    
  • Layer names When referring to layers, format as inline code:

    ``layer name``
    

2.1.5. Labels/references

Anchors inside the text can be used to create hyperlinks to sections or pages.

The example below creates the anchor of a section (e.g., Label/reference title)

.. _my_anchor:

Label/reference
---------------

To call the reference in the same page, use

see my_anchor_ for more information.

which will return:

see my_anchor for more information.

Notice that it will jump to the line/thing following the “anchor”. You do not need to use apostrophes, but you do need to have empty lines after the anchor.

Another way to jump to the same place from anywhere in the documentation is to use the :ref: role.

see :ref:`my_anchor` for more information.

which will create a link with the caption instead (in this case the title of this section!):

see Labels/references for more information.

So, reference 1 (my_anchor) and reference 2 (Labels/references). Because the reference often displays a full caption, it is not really necessary to use the word section. Note that you can also use a custom caption to describe the reference:

see :ref:`Label and reference <my_anchor>` for more information.

which returns:

see Label and reference for more information.

2.1.6. Figures and Images

Pictures

To insert an image, use

.. figure:: /static/common/logo.png
   :width: 10 em

which returns

../../_images/logo.png

Replacement

You can put an image inside text or add an alias to use everywhere. To use an image inside a paragraph, first create an alias in the source/substitutions.txt file:

.. |nice_logo| image:: /static/common/logo.png
               :width: 1 em

and then call it in your paragraph:

My paragraph begins here with a nice logo |nice_logo|.

This is how the example will be displayed:

My paragraph begins here with a nice logo nice_logo.

To allow preview rendering in GitHub that is as close as possible to HTML rendering, you will also need to add the image replacement call at the end of the file you changed. This can be done by copy-pasting it from substitutions.txt or by executing the scripts/find_set_subst.py script.

Nota

Currently, to ensure consistency and help in the use of QGIS icons, a list of aliases is built and available in the Sustituciones chapter.

Figure

.. _figure_logo:

.. figure:: /static/common/logo.png
   :width: 20 em
   :align: center

   A caption: A logo I like

The result looks like this:

../../_images/logo.png

Figura 2.23 A caption: A logo I like

To avoid conflicts with other references, always begin figure anchors with _figure_ and use terms that easily connect to the figure caption. While only the centered alignment is mandatory for the image, feel free to use any other options for figures (such as width, height, scale…) if needed.

The scripts will insert an automatically generated number before the caption of the figure in the generated HTML and PDF versions of the documentation.

To use a caption (see My caption) just insert indented text after a blank line in the figure block.

A figure can be referenced using the reference label like this:

see :numref:`figure_logo`

renders like this:

see Figura 2.23

This is the preferred way of referencing figures.

Nota

For :numref: to work, the figure must have a caption.

It is possible to use :ref: instead of :numref: for reference, but this returns the full caption of the image.

see :ref:`figure_logo`

renders like this:

see A caption: A logo I like

Tables

A simple table can be coded like this

=======  =======  =======
x        y        z
=======  =======  =======
1        2        3
4                 5
=======  =======  =======

It will render like this:

x

y

z

1

2

3

4

5

Use a \ (backslash) followed by an empty space to leave an empty space.

You can also make more complicated tables and reference them:

.. _my_drawn_table:

+---------------+--------------------+
| Windows       | macOS              |
+---------------+--------------------+
| |win|         | |osx|              |
+---------------+--------------------+
| and of course not to forget |nix|  |
+------------------------------------+

My drawn table, mind you this is unfortunately not regarded as a caption

You can reference it like this: my_drawn_table_.

The result:

Windows

macOS

win

osx

y por supuesto no olviden nix

Mi tabla dibujada, ten en cuenta que, lamentablemente, esto no se considera un título

Puedes hacer referencia a él así my_drawn_table.

Para tablas aún más complejas, es más fácil de usar list-table:

.. list-table::
   :header-rows: 1
   :widths: 20 20 20 40

   * - What
     - Purpose
     - Key word
     - Description
   * - **Test**
     - ``Useful test``
     - complexity
     - Geometry.  One of:

       * Point
       * Line

The result:

Que

Propósito

Palabra clave

Descripción

Test

Useful test

complejidad

Geometría. Una de:

  • Punto

  • Línea

2.1.7. Índice

Un índice es una forma práctica de ayudar al lector a encontrar información en un documento. La documentación de QGIS proporciona algunos índices esenciales. Hay algunas reglas que nos ayudan a proporcionar un conjunto de índices que son realmente útiles (coherentes, consistentes y realmente conectados entre sí):

  • Un índice debe ser legible, comprensible y traducible; se puede hacer un índice a partir de muchas palabras, pero debe evitar los caracteres _, - … innecesarios para vincularlos, es decir, Loading layers en lugar de loading_layers o loadingLayers.

  • Escriba en mayúscula solo la primera letra del índice a menos que la palabra tenga una ortografía particular. Por ejemplo, Loading layers, Atlas generation, WMS, pgsql2shp.

  • Esté atento a la lista Índice existente para reutilizar la expresión más conveniente con la ortografía correcta y evitar duplicados innecesarios.

Existen varias etiquetas de índice en RST. Puede utilizar la etiqueta en línea :index: dentro del texto normal:

QGIS can load several :index:`Vector formats` supported by GDAL ...

O puede usar el marcado a nivel de bloque .. index:: que enlaza con el comienzo del siguiente párrafo. Debido a las reglas mencionadas anteriormente, se recomienda utilizar la etiqueta de nivel de bloque:

.. index:: WMS, WFS, Loading layers

También se recomienda utilizar parámetros de índice como single, pair and see, para construir una tabla de índice más estructurada e interconectada. Ver Generación de índices para ams información sobre creación de índices.

2.1.8. Comentarios Especiales

A veces, es posible que desee enfatizar algunos puntos de la descripción, ya sea para advertir, recordar o dar algunas pistas al usuario. En la documentación de QGIS, utilizamos directivas especiales reST como .. warning::, .. seealso::`, ``.. note:: and .. tip::. Estas directivas generan marcos que resaltan sus comentarios. Consulte Marcado de nivel de párrafo para obtener más información. Se requiere un título claro y apropiado tanto para advertencias como para sugerencias.

.. tip:: **Always use a meaningful title for tips**

   Begin tips with a title that summarizes what it is about. This helps
   users to quickly overview the message you want to give them, and
   decide on its relevance.

2.1.9. Fragmentos de código

También puede dar ejemplos e insertar fragmentos de código. En este caso, escriba el comentario debajo de una línea con la directiva ``::”” insertada. Para una mejor representación, especialmente para aplicar resaltado de color al código de acuerdo con su idioma, use la directiva de bloque de código, p. ej. ``.. code-block::xml””. Más detalles en Mostrando código.

Nota

Si bien los textos de los marcos de notas, sugerencias y advertencias son traducibles, tenga en cuenta que los marcos de bloques de código no permiten la traducción. Por lo tanto, evite los comentarios que no estén relacionados con el código y mantenga los comentarios lo más breves posible.

2.1.10. Notas al pie

Tenga en cuenta que ningún software de traducción reconoce las notas a pie de página y tampoco se convierte correctamente a formato pdf. Entonces, si es posible, no use notas al pie de página en ninguna documentación.

Esto es para crear una nota al pie (que se muestra como ejemplo [1])

blabla [1]_

Que apuntará a:

2.2. Manejando Capturas de Pantalla

2.2.1. Adicionar nuevas Capturas de Pantalla

Aquí hay algunas sugerencias para crear capturas de pantalla nuevas y atractivas. Las imágenes deben colocarse en una carpeta de imágenes (img/) que se encuentra en la misma carpeta que el archivo de referencia .rst.

  • Puede encontrar algunos proyectos QGIS preparados que se utilizan para crear capturas de pantalla en la carpeta ./qgis-projects de este repositorio. Esto facilita la reproducción de capturas de pantalla para la próxima versión de QGIS. Estos proyectos utilizan los Datos de muestra de QGIS (también conocidos como Alaska Dataset), que deben descomprimirse y colocarse en la misma carpeta que el repositorio QGIS-Documentation.

  • Reduzca la ventana al espacio mínimo necesario para mostrar la función (tomando toda la pantalla para una pequeña ventana modal> exageración)

  • Cuanto menos desorden, mejor (no es necesario activar todas las barras de herramientas)

  • No los cambie de tamaño en un editor de imágenes; el tamaño se establecerá en los archivos .rst si es necesario (reduciendo las dimensiones sin aumentar adecuadamente la resolución> feo)

  • Cortar el fondo

  • Haga transparentes las esquinas superiores si el fondo no es blanco

  • Establezca la resolución del tamaño de impresión en `` 135 ppp “” (por ejemplo, en Gimp configure la resolución de impresión Imagen -> tamaño de impresión y guarde). De esta forma, las imágenes estarán en tamaño original en html y con una buena resolución de impresión en el PDF. También puede usar el comando de conversión de ImageMagick para hacer un lote de imágenes:

    convert -units PixelsPerInch input.png -density 135 output.png
    
  • Guárdelos como .png (para evitar artefactos .jpeg)

  • La captura de pantalla debe mostrar el contenido de acuerdo con lo que se describe en el texto.

Truco

Si está en Ubuntu, puede usar el siguiente comando para eliminar la función del menú global y crear pantallas de aplicaciones más pequeñas con menús:

sudo apt autoremove appmenu-gtk appmenu-gtk3 appmenu-qt

2.2.2. Capturas de Pantalla Traducidas

Aquí hay algunas sugerencias adicionales para aquellos que desean crear capturas de pantalla para una guía de usuario traducida:

las imágenes trasladadas deben ser ubicadas en la carpeta img/<your_language>/. Utilice el mismo nombre de archivo que la captura de pantalla “original” en inglés.

2.3. Documentando algoritmos de Procesamiento

Si desea escribir documentación para los algoritmos de procesamiento, tenga en cuenta estas pautas:

  • Los archivos de ayuda del algoritmo de procesamiento son parte de la Guía del usuario de QGIS, así que use el mismo formato que la Guía del usuario y otra documentación.

  • La documentación de cada algoritmo debe colocarse en la carpeta proveedor y el archivo grupo correspondientes, p. Ej. el algoritmo Voronoi polygon pertenece al proveedor` QGIS` y al grupo vectorgeometry. Entonces, el archivo correcto para agregar la descripción es: source/docs/user_manual/processing_algs/qgis/vectorgeometry.rst.

    Nota

    Antes de comenzar a escribir la guía, verifique si el algoritmo ya está descrito. En este caso, puede mejorar la descripción existente.

  • Es extremadamente importante que cada algoritmo tenga un vínculo que corresponda al nombre del proveedor + el nombre único del algoritmo en sí. Esto permite que el botón Ayuda abra la página de Ayuda de la sección correcta. El ancla debe colocarse encima del título, p. Ej. (ver también la sección Labels/references ):

    .. _qgisvoronoipolygons:
    
    Voronoi polygons
    ----------------
    

    Para averiguar el nombre del algoritmo, simplemente coloque el mouse sobre el algoritmo en la caja de herramientas de Procesamiento.

  • Evite utilizar «Este algoritmo hace esto y aquello …» como la primera oración en la descripción del algoritmo. Intente usar expresiones más generales como:

    Takes a point layer and generates a polygon layer containing the...
    
  • Evite describir lo que hace el algoritmo replicando su nombre y no repita el nombre del parámetro en la descripción del parámetro en sí. Por ejemplo, si el algoritmo es Polígono de Voronoi, considere la posibilidad de describir la Capa de entrada como Capa desde la que calcular el polígono.

  • Indique en la descripción si el algoritmo tiene un acceso directo predeterminado en QGIS o admite la edición in situ.

  • ¡Añadir imágenes! ¡Una imagen vale mas que mil palabras! Utilice el formato .png y siga las pautas generales para la documentación (consulte la sección Figures and Images para obtener más información). Coloque el archivo de imagen en la carpeta correcta, es decir, la carpeta img junto al .rst que está editando.

  • Si es necesario, agregue enlaces en la sección «Ver también» que brinden información adicional sobre el algoritmo (por ejemplo, publicaciones o páginas web). Solo agregue la sección «Ver también» si realmente hay algo que ver. Como buena práctica, la sección «Ver también» puede llenarse con enlaces a algoritmos similares.

  • Dé una explicación clara de los parámetros y resultados de los algoritmos: inspírese en los algoritmos existentes.

  • Evite duplicar la descripción detallada de las opciones del algoritmo. Agregue esta información en la descripción del parámetro.

  • Evite agregar información sobre el tipo de geometría vectorial en el algoritmo o la descripción del parámetro, ya que esta información ya está disponible en las descripciones de los parámetros.

  • Agregue el valor predeterminado del parámetro, por ejemplo:

    * - **Number of points**
      - ``NUMBER_OF_POINTS``
      - [number]
    
        Default: 1
      - Number of points to create
    
  • Describe el tipo de entrada compatible con los parámetros. Hay varios tipos disponibles entre los que puede elegir:

    Tipo de Parámetro/Salida

    Descripción

    Indicador visual

    Capa vectorial punto

    vector: point

    pointLayer

    Capa vectorial línea

    vector: line

    lineLayer

    Capa vectorial poligonal

    vector: polygon

    polygonLayer

    Capa vectorial genérica

    vector: any

    Campo vectorial numérico

    tablefield: numeric

    fieldFloat

    Campo vectorial cadena

    tablefield: string

    fieldText

    Campo vectorial genérico

    tablefield: any

    Capa ráster

    raster

    rasterLayer

    Banda ráster

    raster band

    Archivo HTML

    html

    Capa tabla

    table

    tableLayer

    Expresión

    expression

    expression

    Geometría punto

    coordinates

    Extensión

    extent

    SRC

    crs

    setProjection

    Enumeración

    enumeration

    selectString

    Lista

    list

    NUmero

    number

    selectNumber

    Cadena

    string

    inputText

    Booleano

    boolean

    checkbox

    Ruta de carpeta

    folder

    Archivo

    file

    Matriz

    matrix

    Capa

    layer

    Mismo tipo de salida que tipo de entrada

    same as input

    Definición

    definition

    Punto

    point

    MultipleLayers

    multipleLayers

    Intervalo

    range

    AuthConfig

    authconfig

    Malla

    mesh

    Diseño

    layout

    Elemento de diseño

    layoutitem

    Color

    color

    Escala

    scale

  • Estudie un algoritmo existente y bien documentado y copie todos los diseños útiles.

  • Cuando haya terminado, simplemente siga las pautas descritas en Una contribución paso a paso para confirmar sus cambios y hacer una Pull Request

Aquí hay un ejemplo de existing algorithm para ayudarte con el diseño y la descripción:

.. _qgiscountpointsinpolygon:

Count points in polygon
-----------------------
Takes a point and a polygon layer and counts the number of points from the
point layer in each of the polygons of the polygon layer.
A new polygon layer is generated, with the exact same content as the input
polygon layer, but containing an additional field with the points count
corresponding to each polygon.

.. figure:: img/count_points_polygon.png
  :align: center

  The labels in the polygons show the point count

An optional weight field can be used to assign weights to each point.
Alternatively, a unique class field can be specified. If both options
are used, the weight field will take precedence and the unique class field
will be ignored.

``Default menu``: :menuselection:`Vector --> Analysis Tools`

Parameters
..........

.. list-table::
   :header-rows: 1
   :widths: 20 20 20 40

   * - Label
     - Name
     - Type
     - Description
   * - **Polygons**
     - ``POLYGONS``
     - [vector: polygon]
     - Polygon layer whose features are associated with the count of
       points they contain
   * - **Points**
     - ``POINTS``
     - [vector: point]
     - Point layer with features to count
   * - **Weight field**

       Optional
     - ``WEIGHT``
     - [tablefield: numeric]
     - A field from the point layer.
       The count generated will be the sum of the weight field of the
       points contained by the polygon.
   * - **Class field**

       Optional
     - ``CLASSFIELD``
     - [tablefield: any]
     - Points are classified based on the selected attribute and if
       several points with the same attribute value are within the
       polygon, only one of them is counted.
       The final count of the points in a polygon is, therefore, the
       count of different classes that are found in it.
   * - **Count field name**
     - ``FIELD``
     - [string]

       Default: 'NUMPOINTS'
     - The name of the field to store the count of points
   * - **Count**
     - ``OUTPUT``
     - [vector: polygon]

       Default: [Create temporary layer]
     - Specification of the output layer type (temporary, file,
       GeoPackage or PostGIS table).
       Encoding can also be specified.

Outputs
.......

.. list-table::
   :header-rows: 1
   :widths: 20 20 20 40

   * - Label
     - Name
     - Type
     - Description
   * - **Count**
     - ``OUTPUT``
     - [vector: polygon]
     - Resulting layer with the attribute table containing the
       new column with the points count