# Barra de título

> La barra superior con los selectores de proyecto y rama. Un componente nativo de Pyzed para GUIs de escritorio en Python, con vista previa, ejemplos y su API.

Source: https://albakore.github.io/pyzed/es/library/title-bar/

:::tip[En pocas palabras]
La barra de lo más alto de la ventana, con el nombre del proyecto y botones rápidos.
:::

La barra superior de la ventana: widgets al principio (`start`, selectores de proyecto y rama), un `center` opcional y widgets al final (`end`, cuenta, notificaciones). `ui.title_button` es el botón compacto que usa (`pyzed ▾`, `main`), con estilos `chevron` y `muted`.

`ui.title_bar` · Categoría: [Espacio de trabajo](https://albakore.github.io/pyzed/es/library/#espacio-de-trabajo) · [Referencia completa →](https://albakore.github.io/pyzed/es/reference/ui/#title_bar)

**Código:**

```python
ui.title_bar(
    [ui.title_button("pyzed", on_projects, chevron=True),
     ui.title_button("main", on_branches, icon="git-branch", muted=True)],
    [ui.facepile(["Ana", "Luis"]), ui.icon_button("bell", on_bell, size="sm"), ui.avatar("KV")],
    center=ui.muted("notes.py"),
)
```

## Cuándo usarlo

- Arriba de un `ui.workspace`, o de cualquier ventana con `decorations=False`.

## Uso

```python
from pyzed import ui

ui.title_bar(
    [ui.title_button("pyzed", on_projects, chevron=True),
     ui.title_button("main", on_branches, icon="git-branch", muted=True)],
    [ui.facepile(["Ana", "Luis"]), ui.icon_button("bell", on_bell, size="sm"), ui.avatar("KV")],
    center=ui.muted("notes.py"),
)
```

## Variantes

:::note[Sobre estas capturas]
Cada captura la graba pyzed mismo, fuera de pantalla a 2x, en One Dark o One Light según el tema de este sitio, y recortada al componente para que se vea a su tamaño real. El puntero pasa por encima, pulsa o escribe en él; un componente que no reacciona al puntero recorre algunos temas. Con movimiento reducido ves el primer fotograma. Abre **Código** bajo una captura para ver el fragmento que la dibuja; los nombres libres como `on_save` son tus propios callbacks.
:::

### Botones de título

```python
ui.title_button("pyzed", on_projects)
```

```python
ui.title_button("pyzed", on_projects, chevron=True)
```

```python
ui.title_button("main", on_branches, icon="git-branch", muted=True)
```

### Barra

```python
pz.container(ui.title_bar([ui.title_button("pyzed", chevron=True)]), width=420)
```

```python
pz.container(ui.title_bar([], [], center=ui.muted("notes.py — Notes")), width=420)
```

```python
pz.container(ui.title_bar([], [ui.icon_button("bell", on_bell, size="sm"), ui.avatar("KV")]), width=420)
```

## Eventos

Barra de título tiene **1 evento propios**, en la tabla de abajo. Como todo widget, también tiene los **18 eventos comunes** (`click`, `double_click`, `right_click`, `mouse_enter`, `drag`, `key_down`, `resize`…), que se conectan con `.on(...)`: mira [Eventos](https://albakore.github.io/pyzed/es/guides/events/) y [Eventos de cada componente](https://albakore.github.io/pyzed/es/library/events/).

| Evento | El handler recibe | Cuándo |
| --- | --- | --- |
| `on_press` | `()` | Mensaje o callable que se envía al pulsar. `None` deshabilita el control. |

**El handler recibe** es lo que Pyzed le pasa a tu función: `()` es nada. Cualquier handler también puede ser un mensaje (un valor que no se puede llamar), que va a `update()`.

### Manejar los eventos

Los mismos eventos escritos de tres formas. **Imperativa**: métodos de la app que cambian `self`. **Declarativa**: los handlers producen mensajes y un único `update()` decide. **Funcional**: una función pura dibuja un estado inmutable y pide cambios con `set_state(...)`. Mira [Imperativo, declarativo y funcional](https://albakore.github.io/pyzed/es/guides/code-styles/).

**Imperativo:**

```python
class Ide(pz.App):
    def __init__(self):
        self.picking = None

    def view(self):
        return ui.title_bar([
            ui.title_button("pyzed", lambda: setattr(self, "picking", "project"), chevron=True),
            ui.title_button("main", lambda: setattr(self, "picking", "branch"), icon="git-branch", muted=True),
        ], center=ui.muted(f"Pick a {self.picking}" if self.picking else "notes.py"))
```

**Declarativo:**

```python
from dataclasses import dataclass

@dataclass
class Pick:
    what: str

class Ide(pz.App):
    picking = None

    def update(self, message):
        match message:
            case Pick(what):
                self.picking = what

    def view(self):
        return ui.title_bar([ui.title_button("pyzed", Pick("project"), chevron=True),
                             ui.title_button("main", Pick("branch"), icon="git-branch", muted=True)])
```

**Funcional:**

```python
from dataclasses import dataclass

@dataclass(frozen=True)
class State:
    project: str = "pyzed"
    projects: tuple = ("pyzed", "notes")

def view(state, set_state):
    nxt = state.projects[(state.projects.index(state.project) + 1) % len(state.projects)]
    return ui.title_bar([ui.title_button(state.project, lambda: set_state(project=nxt), chevron=True)])
```

## Propiedades y API

### `ui.title_bar`

```python
title_bar(start=(), end=(), *, center=None, height=34, theme=None)
```

La barra superior: selectores de proyecto y rama a la izquierda, cuenta y acciones a la derecha.

| Propiedad | Por defecto | Descripción |
| --- | --- | --- |
| `start` | `()` | Widgets al inicio (izquierda). |
| `end` | `()` | Widgets al final (derecha). |
| `center` | `None` | Widget centrado. |
| `height` | `34` | Alto. |
| `theme` | `None` | Tema a usar en lugar del actual (`pyzed.theme.current()`). |

[Referencia completa →](https://albakore.github.io/pyzed/es/reference/ui/#title_bar)

### `ui.title_button`

```python
title_button(
    content,
    on_press=None,
    *,
    icon=None,
    muted=False,
    chevron=False,
    theme=None,
)
```

Un botón compacto para la barra de título (`pyzed ▾`, `main`…).

| Propiedad | Por defecto | Descripción |
| --- | --- | --- |
| `content` | *obligatorio* | Texto. |
| `icon` | `None` | Nombre de un icono de Lucide (`pyzed icons` los lista). |
| `muted` | `False` | Texto atenuado. |
| `chevron` | `False` | Añade un ▾. |
| `theme` | `None` | Tema a usar en lugar del actual (`pyzed.theme.current()`). |

Eventos: `on_press` ([eventos](#eventos)).

[Referencia completa →](https://albakore.github.io/pyzed/es/reference/ui/#title_button)

## Relacionados

- [Espacio de trabajo](https://albakore.github.io/pyzed/es/library/workspace/): La disposición de una ventana estilo editor: barra de título, docks, centro y barra de estado.
- [Barra de estado](https://albakore.github.io/pyzed/es/library/status-bar/): La barra inferior: diagnósticos, posición del cursor, lenguaje.
- [Facepile](https://albakore.github.io/pyzed/es/library/facepile/): Avatares de colaboradores superpuestos con +N.
- [Marco de ventana](https://albakore.github.io/pyzed/es/library/window-frame/): Tu propia barra de título, botones de ventana y menús.
