Saltar a contenido

Formulario de atributos

Antes de acceder al campo, deberá configurar sus formularios (los campos que el usuario verá). Puede crear los formularios en su proyecto de QGIS. Funciona igual que en un proyecto QGIS normal, pero con algunas diferencias.

Configuración del formulario de atributo

Para configurar un formulario, debes abrir Propiedades > Formulario de atributos de la capa vectorial en QGIS.

Dependiendo del comportamiento que desee para sus diferentes atributos, puede elegir diferentes tipos de widgets. A continuación, se muestra un resumen de los tipos de widgets disponibles y compatibles.

Tipo de control Soporte Notas
Edición de texto - No se admite HTML.
- La entrada numérica se aplica en función del tipo de campo.
Casilla de verificación
Mapa de valores menú desplegable o botón de opción (exclusivo de QField únicamente)
Oculto
Adjunto This field is combined with camera integration.
It is also able to open other files like pdf and doc (if you have an appropriate viewer) Attachment (photo settings)
Fecha Hora
Rango
Referencia de relación
Editor de relaciones
Relación de valores
Generador de UUID
Control QML / HTML
Otros Funding

Configuración general de atributos

In order to customize the attribute form, it is necessary to use the drag and drop designer in QGIS or to a use pre-written UI file. You can also make use of powerful expressions to populate the different fields. Additionally, to the ones available there are QFieldCloud specific variables, which can be utilized inside the attribute form:

A continuación se muestran algunas otras configuraciones generales útiles, que puede encontrar en el formulario Propiedades... > Atributos de la capa vectorial (ver la imagen a continuación).

  • Diseñador de arrastrar y soltar: puede estructurar sus formularios utilizando varios contenedores, como pestañas y grupos, y mejorar la interactividad incorporando visibilidad condicional de los campos y asignando valores predeterminados. Para obtener más información, consulte: Documentación del Diseñador de arrastrar y soltar de QGIS

  • Ocultar formulario de atributo al: Puede ocultar el formulario de atributo cambiando de "Mostrar formulario al agregar función" a la configuración "Suprimir formulario de atributo". Al agregar una nueva característica en QField, no es necesario completar ningún formulario de atributo. Nota: En tal caso, debe configurar el formulario de atributos de tal manera que se cumplan todas las restricciones/reglas incluso si no agrega ningún atributo.

  • Editable: Puedes decidir si un campo es editable o no activándolo en la visualización del widget del campo correspondiente.
  • Recordar los últimos valores: Si no desea agregar el mismo valor una y otra vez, puede habilitar esta opción en la visualización del widget en QGIS. Sin embargo, QField ofrece un control más detallado sobre los últimos valores utilizados. Si habilita esta opción en QGIS, la regla siempre se aplicará. Con QField puedes cambiar y deshabilitar esta opción en cualquier momento durante la recopilación de datos.

General Attribute Form
General Attribute Form

Working with Relations

Preparación en escritorio

For detailed information on setting up layer relations in QGIS, please refer to the setting relations between multiple layers section in the QGIS documentation.

To further control the visibility and number of related items shown in QField, see the instructions for configuring Maximum items visibility for QField.

El widget de relación muestra todas las características secundarias de referencia en una lista. Si está habilitado, es posible añadirlas, eliminarlas y abrirlas.

The visual identification of the list entries is done via the Display Expression of the child layer.

Manejo de claves

Since the parent primary key is used as foreign key in the referencing child features, the primary key must be safe to use (it must be unique) also after syncronizing back to the desktop. Therefore we always recommend to use UUIDs as primary keys. See Working with GeoPackages for further information.

You can already add children from a parent that is about to be added. This option will be blocked if there is no valid primary key on the parent or the constraints are violated. In case the adding of the parent feature is canceled after some children have been added already, the children are deleted as well.

Relaciones Muchos-a-Muchos

On many-to-many relationships, according to the cardinality setting in the QGIS Vector Layer Properties..., on adding, deleting or opening an entry in the list effects directly the child layer (on direct cardinality) or the linking table (on many-to-one cardinality).

El segundo caso se usa habitualmente cuando hay una información adicional sobre la relación (ej. porcentaje) en la tabla enlazada.

En caso de cardinalidad muchos a uno en relaciones muchos a muchos, es necesario establecer la Expresión de visualización en la tabla de enlace.

Ordered Relation

If required you can reorder linked child features based on a field by selecting the Ordered Relation Editor from the widget type options. To enable this functionality, however, you require a second plugin Ordered Relation Editor

Flujo

  1. Install the Plugin Ordered Relation Editor plugin from the official repository or through the "Plugin Manager" in QGIS.

  2. Open the Vector Layer Properties... > Attributes Form and set the layout editor to Drag and Drop Designer.

  3. Click on the relationship of your available widgets.

  4. On the right under "Widget Display" scroll down to the "Widget Type option and select Ordered Relation Editor.

  5. Configure the widget using the following settings:

  6. Ordering Field: Specify the field in the child layer that will be used to determine the order of the features.

  7. Description: Define an expression to be displayed for each child feature in the list.

  8. Image Path (Optional): Provide a path to an image or icon to visually enhance the list. This is an expression that resolves dynamically.

Widget configuration in QGIS
Widget configuration in QGIS

QField
QField

Configuración del widget Mapa de valores

When using value maps as a widget type you can control the automatic switch from a "buttons'" interface to a list

QFieldSync Layer Properties
QFieldSync Layer Properties
.

Flujo

  1. Direct to the Vector Layer Properties > QField

  2. Under the "Feature Form Settings" enable and define quantity of items that will trigger the transition to a toggle button interface.

QField Value Map Editor as List
QField Value Map Editor as List

QField Value Map Editor as Buttons
QField Value Map Editor as Buttons

Widget de archivos adjuntos

Preparación en escritorio

El tipo de widget Archivo adjunto se utiliza con campos que almacenan la ruta de acceso a los archivos.

Se puede usar para:

  • Muestra y toma fotos o agrega imágenes desde la galería.
  • Escuchar y grabar clips de sonido
  • Mostrar y grabar vídeos
  • Mostrar enlaces a archivos externos como PDF o documentos
  • Agregue bocetos directamente en QField

Form attachment picture
Form attachment picture

Form attachment audio
Form attachment audio

Form attachment video
Form attachment video

Nota

La ruta debe ser "relativa". Las imágenes, audios, vídeos, archivos PDF y documentos se almacenan en un subdirectorio del proyecto, al que apunta el enlace del campo de texto.

Puedes añadir un nuevo elemento al hacer clic en la opción de cámara, vídeo, micrófono o documento. Según la opción predeterminada que hayas seleccionado, se mostrará una de ellas dentro del formulario.

Media
Media

Al Sincronizar también se debe copiar el subdirectorio con las imágenes, vídeos, audios, PDF y documentos.

De forma predeterminada, al añadir archivos adjuntos, QField muestra el archivo automáticamente. La opción hipervínculo en el widget de adjuntos deshabilitará esta función y mostrará solo la ruta al hipervínculo del archivo.

Flujo

Establecer una ruta de archivo adjunto específica

Desktop preparation

In QFieldSync you can configure the path of attachments. By default, pictures are saved into the "DCIM" folder, audio recordings are saved into the "audio" folder and videos are saved into "video" with a timestamp as name.

  1. Direct to the Properties > QField > Attachments Settings
  2. Use specific expressions to set the required names of the attachments.

Paths
Paths

Widget de relación de valores

Preparación en escritorio

El widget Relación de valores ofrece valores de una tabla relacionada en un cuadro combinado. Aquí tiene varias opciones para elegir:

  • Capa: Establezca la tabla o capa que almacena los valores que se seleccionarán.
  • Columna clave: establece la columna que contiene los valores que se guardarán.
  • columna de valores: establece la columna real que contiene los valores que se mostrarán durante la recopilación.

  • Ordenar por valor: establece el orden en que deben mostrarse los valores mostrados. Esto puede ser por "clave", "valor" o una columna específica.

  • Columna de grupo: puedes agrupar tus valores en función de otra columna. (por ejemplo, si desea recopilar información sobre especies de árboles, puede agrupar los valores por género).
  • Permitir valor NULO: el campo puede permanecer en blanco.
  • Usar Completador: Puede utilizar esta opción para completar automáticamente sus campos. Al seleccionar la lupa, puede buscar entre los valores disponibles y seleccionar el que corresponda.
  • Permitir selecciones múltiples: si está habilitado, puede seleccionar múltiples valores en una función.

Flujo

Group Value Configuration

  1. Choose the column that will be used to organize the items. The values from this column will act as group title.

  2. (Optional) Enable Display group name if you want to add the title of your group as a distinct header. This creates a clear separation between the different groups, making the list easier to navigate.

First configuration
First configuration

Second configuration
Second configuration

Third configuration
Third configuration

Different configurations on QField
Different configurations on QField

Flujo

Use Auto Complete

  1. Direct to Vector Layer Properties... > Attributes Form.

  2. Your widget type needs to be "Value Relation".

  3. Enable the "Use completer" option.

Enable auto-complete within QGIS
Enable auto-complete within QGIS

Here is a video showing how it works on QField

Visibilidad condicional

Preparación en escritorio

Puede ocultar grupos enteros según expresiones. Esto es útil cuando ciertos atributos solo se requieren en determinadas circunstancias.

Flujo

Example: Accessing the status of tree species

Some of them might have a disease and you have a list of possible diseases.

A typical step-by-step workflow could look like this:

  1. Create a group.

  2. Define a visibility expression for the group. Eg. Only if the tree is marked as "sick", the field "disease" will appear.

  3. Add the field that is to be shown only after the expression criteria is set into the group. Eg. We will add our "type of disease" field into the group.

Configuration of a group box that will only be shown if the checkbox "disease" is checked.
Configuration of a group box that will only be shown if the checkbox "disease" is checked.

In QField it will look like in the video below.

Definir Restricciones

Preparación en escritorio

Los campos de atributos pueden tener restricciones asociadas. Las restricciones son reglas en forma de expresiones. Antes de poder guardar una característica, deben cumplirse todas las restricciones. Se puede añadir una descripción que se mostrará si no se cumple una restricción.

Configuration of a constraint within a range
Configuration of a constraint within a range

¡¡¡Ejemplos!!! No se puede introducir un valor de elevación superior a la montaña más alta de este país.

``` sql
"elevation" < 5000
```

*It is required to fill in an identifier.*

``` sql
"identifier" IS NOT NULL
```

Definir Valores Predeterminados

Preparación en escritorio

Los campos pueden tener valores predeterminados configurados. Los valores predeterminados se insertan en el formulario de atributos al digitalizar una nueva característica. Son visibles y se pueden modificar siempre que el campo sea editable.

Configuration of a formatted date as default value
Configuration of a formatted date as default value

Atención

La opción "Aplicar valor predeterminado al actualizar" debe utilizarse con cuidado y no para campos que actúan como claves principales.

Trabajar con expresiones

Al crear expresiones para proyectos destinados a ser utilizados con QField, se recomienda utilizar nombres de capas en lugar de ID de capas. Esta recomendación se debe a que, durante el proceso de conversión del proyecto a través de QFieldSync, las capas resultantes pueden recibir ID diferentes, lo que puede dar lugar a evaluaciones incorrectas de las expresiones. Al utilizar nombres de capas, se garantiza que las expresiones se evalúen de forma coherente y precisa en los diferentes estados del proyecto.

Using layer names in expressions
Using layer names in expressions

Variables adicionales

For more information regarding storing information related to your position in object attributes, refer to the dedicated GNSS documentation.

Para los usuarios de QFieldCloud, se pueden utilizar dos variables en las expresiones que incluyen los valores predeterminados de los formularios de atributos:

  • @cloud_username que devuelve el nombre del usuario actualmente conectado a QFieldCloud.
  • @cloud_useremail que devuelve la dirección de correo electrónico del usuario actualmente conectado a QFieldCloud.

Ejemplos

Insertar información de posicionamiento como variable:

@position_horizontal_accuracy

Insert the current date and time:

now()

Insert the length of the digitized line:

length($geometry)

Configurar variables globales en el dispositivo e insertarlas.

@operator_name

Si desea asignar un código de región según la ubicación donde se inserta una nueva característica, puede hacerlo utilizando una expresión agregada:

aggregate( layer:='regions', aggregate:='max', expression:="code", filter:=intersects( $geometry, geometry( @parent ) ) )

Para transformar las coordenadas recibidas de \@position_coordinate al sistema de coordenadas de su proyecto:

x(transform(@position_coordinate, 'EPSG:4326', @project_crs))
y(transform(@position_coordinate, 'EPSG:4326', @project_crs))

Si desea utilizar los resultados de ajuste después de dibujar una línea, puede utilizar la variable @snapping_results. El siguiente código extrae el valor del atributo id de la coincidencia de ajuste del primer punto de una línea.

with_variable(
  'first_snapped_point',
  array_first( @snapping_results ),
  attribute(
    get_feature_by_id(
      @first_snapped_point['layer'],
      @first_snapped_point['feature_id']
    ),
    'id'
  )
)

Búsqueda en controles de relación de valores y de referencia de la relación

Es posible buscar valores en un widget de relación de valores o referencia de relación utilizando la lupa situada junto al campo.

Note

Define the display expression for the concerned layers, this will be used for searching for features. This is configured under Vector Layer Properties... > Display

Definir controles QML

Los widgets QML personalizados pueden ser útiles para integrar acciones avanzadas en formularios.

Ejemplo

We define add a button that open a third-party map and navigation app. This is useful to open e.g. turn-by-turn navigation on the device-native app for the user.

import QtQuick 2.0
import QtQuick.Controls 2.0

Button {
    width: 200
    height: width/5
    text: "Open in Maps"
    onClicked: {
        Qt.openUrlExternally(expression.evaluate("'geo:0,0?q=' || $y || ',' || $x"));
    }
}

The geo URI above is adapted to work with Android. For Apple Maps the URI can be changed to 'geo:' || $y || ',' || $x.