# Componentes

Los componentes son widgets interactivos que permiten a los usuarios configurar parámetros (inputs) o ver resultados dentro de tu bloque personalizado.

{% hint style="info" %}
Los componentes se construyen mediante argumentos por palabra clave (keyword arguments).
{% endhint %}

#### Argumentos genéricos

Los argumentos genéricos se aplican a todos los componentes personalizados. Puedes pasarlos como keyword arguments a los constructores.

En lugar de repetirlos para cada componente, aquí tienes una pequeña referencia en estilo “pyi”:

```python
# Common keyword arguments (supported by all components)
class _CommonComponentKwargs:
    def __init__(
        self,
        *,
        tool_tip: str = "",
        enabled: bool = True,
        hidden: bool = False,
        fixed_width: int = 0,
        fixed_height: int = 0,
        minimum_width: int = 0,
        minimum_height: int = 0,
        maximum_width: int = 0,
        maximum_height: int = 0,
        serializable: bool = True,
        stylesheet: str = "",
        font_size: int = -1,
        font_bold: bool = False,
        alignment: str = "AlignLeft",
        **kwargs,
    ) -> None: ...
```

Notas:

* `tool_tip` controla la ayuda (tooltip) mostrada al pasar el cursor sobre el componente.
* `fixed_width` / `fixed_height` están en píxeles. Usa `0` para “automático”.
* Algunos componentes sobrescriben valores por defecto (por ejemplo `DropDown` no es serializable; `Image` no es serializable por defecto).

### Text Input

Permite a los usuarios introducir texto o números en una sola línea.

!\[]\(.assets/gitbook/image (50).png)

```python
# pyi-style reference
class TextInput:
    def __init__(
        self,
        *,
        text: str = "",
        place_holder: str = "",
        check_type: type = str,
        password: bool = False,
        tool_tip: str = "",
        **kwargs,
    ) -> None: ...

    @property
    def value(self) -> str: ...

    @property
    def text(self) -> str: ...  # same as .value

    def toInt(self) -> int: ...
    def toFloat(self) -> float: ...
```

Notas:

* Usa `check_type=int` o `check_type=float` para restringir lo que el usuario puede teclear.
* Usa `.toInt()` / `.toFloat()` cuando quieras que los errores de conversión aparezcan con una excepción clara (sin fallback silencioso).

Ejemplo:

```python
class Example_Block(Block):
    ...
    def init(self):
        ...
        self.param["text1"] = TextInput(
            text="5",
            place_holder="Enter an integer",
            check_type=int,
            tool_tip="Defines constant",
        )
    
    def run(self):
        ...
        constant: int = self.param["text1"].toInt()
        ... 
```

### Drop Down List

Las listas desplegables permiten a los usuarios elegir una opción de una lista de textos.

!\[]\(.assets/gitbook/image (49).png)

```python
# pyi-style reference
class DropDown:
    serializable: bool = False

    def __init__(
        self,
        *,
        items: list[str] | dict[str, object] = ["item1", "item2", "item3"],
        selected_index: int = 0,
        tool_tip: str = "",
        **kwargs,
    ) -> None: ...

    @property
    def selected_item(self) -> str: ...

    @property
    def selected_index(self) -> int: ...
```

Notas:

* Si pasas `items` como un `dict[str, object]`, puedes acceder al valor mapeado mediante `.getCurrentMatch()`.

{% hint style="warning" %}
`DropDown` actualmente está marcado como no serializable. Si quieres que la selección persista en escenarios guardados, guarda `selected_index` tú mismo (por ejemplo con `register_ser_value()` o `serialize_node()`).
{% endhint %}

Ejemplo:

```python
class Example_Block(Block):
    ...
    def init(self):
        ...
        self.param['drop_down'] = DropDown(items=['Method 1', 'Method 2', 'Method 3'], 
                                        tool_tip='Choose Method')
    
    def run(self):
        ...
        method_index: int = self.param['drop_down'].selected_index
        method_name: str = self.param['drop_down'].selected_item
        if method_index == 0:
            ... 
```

### Label

Los labels son componentes de texto simples para mostrar texto estático o dinámico en tu bloque personalizado.

!\[]\(.assets/gitbook/image (54).png)

También se usan para informar sobre componentes interactivos:

!\[]\(.assets/gitbook/image (53).png)

```python
# pyi-style reference
class Label:
    def __init__(self, *, text: str = "", tool_tip: str = "", **kwargs) -> None: ...
    def set_text(self, text: str) -> None: ...
```

Ejemplo:

```python
class Example_Block(Block):
    ...
    def init(self):
        ...
        self.param['label'] = Label(text='Result is: Not Set', 
                                        tool_tip='Shows mean value')
    
    def run(self):
        ...
        self.param['label'].set_text(f'Result is: {n}')
        ... 
```

### Slider

Restringe la entrada del usuario a un rango numérico.

!\[]\(.assets/gitbook/image (55).png)

```python
# pyi-style reference
class Slider:
    def __init__(
        self,
        *,
        min: int = 0,
        max: int = 100,
        val: int = 50,
        tool_tip: str = "",
        **kwargs,
    ) -> None: ...

    @property
    def value(self) -> float | int: ...
```

Ejemplo:

```python
class Example_Block(Block):
    ...
    def init(self):
        ...
        self.param['slider'] = Slider(min=-5, max=5, val=3)
    
    def run(self):
        ...
        threshold: int = self.param['slider'].value
        ... 
```

### Slider Labeled

Igual que [Slider](#slider) pero añade una etiqueta que muestra automáticamente el valor actual del componente.

!\[]\(.assets/gitbook/image (56).png)

```python
# pyi-style reference
class SliderLabeled:
    def __init__(
        self,
        *,
        min: int = 0,
        max: int = 100,
        val: int = 50,
        label: str = "Value",
        multiplier: float | int = 1,
        add: float | int = 0,
        tool_tip: str = "",
        **kwargs,
    ) -> None: ...

    @property
    def value(self) -> float | int: ...

    @property
    def modifiedValue(self) -> float | int: ...
```

Ejemplo:

```python
class Example_Block(Block):
    ...
    def init(self):
        ...
        self.param['threshold_odd'] = SliderLabeled(min= -5, max= 5, val= 3, label="Value", multiplier = 2, add = -1)
    
    def run(self):
        ...
        threshold_odd: int = self.param['threshold_odd'].modifiedValue
        ... 
```

### CheckBox

Permite entrada de estado lógico (true/false).

!\[]\(.assets/gitbook/image (43).png)

```python
# pyi-style reference
class CheckBox:
    def __init__(
        self,
        *,
        text: str = "",
        init_state: bool = False,
        tool_tip: str = "",
        **kwargs,
    ) -> None: ...

    @property
    def is_checked(self) -> bool: ...
```

Ejemplo:

```python
class Example_Block(Block):
    ...
    def init(self):
        ...
        self.param['gray_mode'] = CheckBox(text=': Gray Mode')
    
    def run(self):
        ...
        flag_gray: bool = self.param['gray_mode'].is_checked
        ... 
```

### Button

Dispara un evento en tu script al hacer clic con el ratón. Este componente también es muy útil para la gestión de recursos en bloques personalizados dentro del escenario.

!\[]\(.assets/gitbook/image (44).png)

```python
# pyi-style reference
from collections.abc import Callable

class Button:
    def __init__(self, *, text: str = "", tool_tip: str = "", **kwargs) -> None: ...
    def set_clicked_callback(self, callback: Callable[[], None]) -> None: ...
```

{% hint style="info" %}
Usa `set_clicked_callback(...)` dentro de `init()`.
{% endhint %}

Ejemplo:

```python
...
class Example_Block(Block):
    ...
    file_path: str = ''
    def init(self):
        ...
        self.param['Choose File'] = Button(text= 'Choose File')
        self.param['Choose File'].set_clicked_callback(self.load_image)
    
    def load_image(self):
        path = QAFileDialog.getOpenFileName(caption='Load Image', 
                                        directory='C:/Images', 
                                        filter='Image Files (*.png *.jpg *.bmp)')
        self.file_path = self.register_resource('image-path', path)
        
    def run(self):
        image_path = self.get_resource('image-path')
    
```

El ejemplo anterior utiliza callbacks junto con [`register_resource`](https://docs.augelab.com/spanish/caracteristicas-clave/coding-reference#blockregister_resourcename-str-path-str-str) y [`get_resource`](https://docs.augelab.com/spanish/caracteristicas-clave/coding-reference#blockget_resourcename-str-str).

### Image

!\[]\(.assets/gitbook/image (45).png)

```python
# pyi-style reference
import numpy as np
import numpy.typing as npt

class Image:
    def __init__(
        self,
        *,
        fixed_width: int = 80,
        fixed_height: int = 80,
        tool_tip: str = "",
        serializable: bool = False,
        **kwargs,
    ) -> None: ...

    def update(self, img: npt.NDArray[np.uint8]) -> None: ...
```

Ejemplo:

```python
...
class Example_Block(Block):
    def init(self):
        ...
        self.param['Result'] = Image(
            fixed_width=self.width - 40,
            fixed_height=self.height - 80,
        )

    def run(self):
        ...
        self.param['Result'].update(np.zeros((60, 60, 3), dtype=np.uint8))
        ...
```

### Table

Permite seleccionar varios ítems/modos al mismo tiempo.

!\[]\(.assets/gitbook/image (46).png)

```python
# pyi-style reference
class Table:
    def __init__(
        self,
        *,
        header_label: str = "table",
        items: list[str] | dict[str, bool] = ["item1", "item2", "item3"],
        tool_tip: str = "",
        **kwargs,
    ) -> None: ...

    @property
    def items(self) -> list[str]: ...

    @property
    def selected_items(self) -> list[str]: ...

    def set_items(self, items: list[str]) -> None: ...
```

Ejemplo:

```python
...
class Example_Block(Block):
    def init(self):
        ...
        self.param['Detection List'] = Table(items=['Human', 'Cat', 'Dog'])

    def run(self):
        ...
        detection_list: list[str, ...] = self.param['Detection List'].selected_items
        ...
```

### Text Edit

Text Edit es un área de texto de múltiples líneas.

```python
# pyi-style reference
class TextEdit:
    def __init__(self, *, text: str = "", tool_tip: str = "", **kwargs) -> None: ...

    @property
    def value(self) -> str: ...

    @property
    def text(self) -> str: ...  # same as .value
```

Ejemplo:

```python
class Example_Block(Block):
    def init(self):
        self.param['notes'] = TextEdit(tool_tip='Write notes here')

    def run(self):
        notes: str = self.param['notes'].value
```
