Control¶
Inherits: CanvasItem < Node < Object
Inherited By: BaseButton, ColorRect, Container, GraphEdit, ItemList, Label, LineEdit, NinePatchRect, Panel, Popup, Range, ReferenceRect, RichTextLabel, Separator, Tabs, TextEdit, TextureRect, Tree, VideoPlayer
Todos los nodos de la interfaz de usuario heredan de Control. Los anclajes y márgenes de un control adaptan su posición y tamaño en relación con su padre..
Descripción¶
Base class for all UI-related nodes. Control
features a bounding rectangle that defines its extents, an anchor position relative to its parent control or the current viewport, and margins that represent an offset to the anchor. The margins update automatically when the node, any of its parents, or the screen size change.
For more information on Godot's UI system, anchors, margins, and containers, see the related tutorials in the manual. To build flexible UIs, you'll need a mix of UI elements that inherit from Control
and Container nodes.
User Interface nodes and input
Godot sends input events to the scene's root node first, by calling Node._input. Node._input forwards the event down the node tree to the nodes under the mouse cursor, or on keyboard focus. To do so, it calls MainLoop._input_event. Call accept_event so no other node receives the event. Once you accept an input, it becomes handled so Node._unhandled_input will not process it.
Only one Control
node can be in keyboard focus. Only the node in focus will receive keyboard events. To get the focus, call grab_focus. Control
nodes lose focus when another node grabs it, or if you hide the node in focus.
Sets mouse_filter to MOUSE_FILTER_IGNORE to tell a Control
node to ignore mouse or touch events. You'll need it if you place an icon on top of a button.
Theme resources change the Control's appearance. If you change the Theme on a Control
node, it affects all of its children. To override some of the theme's parameters, call one of the add_*_override
methods, like add_font_override. You can override the theme with the inspector.
Note: Theme items are not Object properties. This means you can't access their values using Object.get and Object.set. Instead, use get_color, get_constant, get_font, get_icon, get_stylebox, and the add_*_override
methods provided by this class.
Tutoriales¶
Propiedades¶
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
Métodos¶
_clips_input ( ) virtual |
|
_get_minimum_size ( ) virtual |
|
void |
_gui_input ( InputEvent event ) virtual |
_make_custom_tooltip ( String for_text ) virtual |
|
void |
accept_event ( ) |
void |
add_color_override ( String name, Color color ) |
void |
add_constant_override ( String name, int constant ) |
void |
add_font_override ( String name, Font font ) |
void |
add_icon_override ( String name, Texture texture ) |
void |
add_shader_override ( String name, Shader shader ) |
void |
add_stylebox_override ( String name, StyleBox stylebox ) |
can_drop_data ( Vector2 position, Variant data ) virtual |
|
void |
|
find_next_valid_focus ( ) const |
|
find_prev_valid_focus ( ) const |
|
void |
force_drag ( Variant data, Control preview ) |
get_anchor ( Margin margin ) const |
|
get_begin ( ) const |
|
get_combined_minimum_size ( ) const |
|
get_constant ( String name, String theme_type="" ) const |
|
get_cursor_shape ( Vector2 position=Vector2( 0, 0 ) ) const |
|
get_drag_data ( Vector2 position ) virtual |
|
get_end ( ) const |
|
get_focus_neighbour ( Margin margin ) const |
|
get_focus_owner ( ) const |
|
get_global_rect ( ) const |
|
get_margin ( Margin margin ) const |
|
get_minimum_size ( ) const |
|
get_parent_area_size ( ) const |
|
get_parent_control ( ) const |
|
get_rect ( ) const |
|
get_rotation ( ) const |
|
get_stylebox ( String name, String theme_type="" ) const |
|
get_theme_default_font ( ) const |
|
get_tooltip ( Vector2 at_position=Vector2( 0, 0 ) ) const |
|
void |
grab_click_focus ( ) |
void |
grab_focus ( ) |
has_color_override ( String name ) const |
|
has_constant ( String name, String theme_type="" ) const |
|
has_constant_override ( String name ) const |
|
has_focus ( ) const |
|
has_font_override ( String name ) const |
|
has_icon_override ( String name ) const |
|
has_shader_override ( String name ) const |
|
has_stylebox ( String name, String theme_type="" ) const |
|
has_stylebox_override ( String name ) const |
|
void |
|
void |
release_focus ( ) |
void |
set_anchor ( Margin margin, float anchor, bool keep_margin=false, bool push_opposite_anchor=true ) |
void |
set_anchor_and_margin ( Margin margin, float anchor, float offset, bool push_opposite_anchor=false ) |
void |
set_anchors_and_margins_preset ( LayoutPreset preset, LayoutPresetMode resize_mode=0, int margin=0 ) |
void |
set_anchors_preset ( LayoutPreset preset, bool keep_margins=false ) |
void |
|
void |
set_drag_forwarding ( Control target ) |
void |
set_drag_preview ( Control control ) |
void |
|
void |
set_focus_neighbour ( Margin margin, NodePath neighbour ) |
void |
set_global_position ( Vector2 position, bool keep_margins=false ) |
void |
set_margin ( Margin margin, float offset ) |
void |
set_margins_preset ( LayoutPreset preset, LayoutPresetMode resize_mode=0, int margin=0 ) |
void |
set_position ( Vector2 position, bool keep_margins=false ) |
void |
set_rotation ( float radians ) |
void |
|
void |
show_modal ( bool exclusive=false ) |
void |
warp_mouse ( Vector2 to_position ) |
Señales¶
focus_entered ( )
Se emite cuando el nodo obtiene el foco del teclado.
focus_exited ( )
Emitido cuando el nodo pierde el foco del teclado.
gui_input ( InputEvent event )
Emitido cuando el nodo recibe un InputEvent.
minimum_size_changed ( )
Emitido cuando el tamaño mínimo del nodo cambia.
modal_closed ( )
Emitted when a modal Control
is closed. See show_modal.
mouse_entered ( )
Emitted when the mouse enters the control's Rect
area, provided its mouse_filter lets the event reach it.
Note: mouse_entered will not be emitted if the mouse enters a child Control
node before entering the parent's Rect
area, at least until the mouse is moved to reach the parent's Rect
area.
mouse_exited ( )
Emitted when the mouse leaves the control's Rect
area, provided its mouse_filter lets the event reach it.
Note: mouse_exited will be emitted if the mouse enters a child Control
node, even if the mouse cursor is still inside the parent's Rect
area.
resized ( )
Emitido cuando el control cambia de tamaño.
size_flags_changed ( )
Emitido cuando una de las flags de tamaño cambia. Ver size_flags_horizontal y size_flags_vertical.
Enumeraciones¶
enum FocusMode:
FOCUS_NONE = 0 --- El nodo no puede captar el foco. Usar con focus_mode.
FOCUS_CLICK = 1 --- El nodo sólo puede captar el foco en los clics del ratón. Usar con focus_mode.
FOCUS_ALL = 2 --- El nodo sólo puede captar el foco en los clics del ratón. Usar con focus_mode.
enum CursorShape:
CURSOR_ARROW = 0 --- Mostrar el cursor del ratón de la flecha del sistema cuando el usuario pasa por encima del nodo. Usar con mouse_default_cursor_shape.
CURSOR_IBEAM = 1 --- Muestra el cursor del ratón del sistema I-beam cuando el usuario pasa por encima del nodo. El puntero del I-beam tiene una forma similar a la de la "I". Le dice al usuario que puede resaltar o insertar texto.
CURSOR_POINTING_HAND = 2 --- Muestra el cursor del ratón de la mano del sistema cuando el usuario pasa por encima del nodo.
CURSOR_CROSS = 3 --- Muestra el cursor cruzado del ratón del sistema cuando el usuario pasa por encima del nodo.
CURSOR_WAIT = 4 --- Muestra el cursor del ratón de espera del sistema, a menudo un reloj de arena, cuando el usuario pasa por encima del nodo.
CURSOR_BUSY = 5 --- Muestra el cursor del ratón ocupado del sistema cuando el usuario pasa por encima del nodo. A menudo un reloj de arena.
CURSOR_DRAG = 6 --- Muestra el cursor del ratón de arrastre del sistema, a menudo un puño cerrado o un símbolo de cruz, cuando el usuario pasa por encima del nodo. Le dice al usuario que está arrastrando un elemento, como un nodo en el Dock de la escena.
CURSOR_CAN_DROP = 7 --- Muestra el cursor del ratón del sistema cuando el usuario pasa por encima del nodo. Puede ser una mano abierta. Le dice al usuario que puede soltar un elemento que está agarrando, como un nodo en el Dock de la escena.
CURSOR_FORBIDDEN = 8 --- Muestra el cursor del ratón prohibido del sistema cuando el usuario pasa por encima del nodo. A menudo un círculo cruzado.
CURSOR_VSIZE = 9 --- Muestra el cursor del ratón de tamaño vertical del sistema cuando el usuario pasa por encima del nodo. Una flecha vertical de doble punta. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel verticalmente.
CURSOR_HSIZE = 10 --- Muestra el cursor del ratón de tamaño horizontal del sistema cuando el usuario pasa por encima del nodo. Una flecha horizontal de doble punta. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel horizontalmente.
CURSOR_BDIAGSIZE = 11 --- Muestra el cursor de cambio de tamaño de la ventana del sistema del ratón cuando el usuario pasa por encima del nodo. El cursor es una flecha de doble punta que va de abajo a la izquierda a arriba a la derecha. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel tanto horizontal como verticalmente.
CURSOR_FDIAGSIZE = 12 --- Muestra el cursor del cambio de tamaño de la ventana del sistema cuando el usuario pasa por encima del nodo. El cursor es una flecha de doble punta que va de arriba a la izquierda a abajo a la derecha, lo opuesto a CURSOR_BDIAGSIZE. Le dice al usuario que puede cambiar el tamaño de la ventana o del panel tanto horizontal como verticalmente.
CURSOR_MOVE = 13 --- Muestra el cursor del ratón del sistema cuando el usuario pasa por encima del nodo. Muestra 2 flechas de doble cabeza en un ángulo de 90 grados. Le dice al usuario que puede mover libremente un elemento de la interfaz de usuario.
CURSOR_VSPLIT = 14 --- Muestra el cursor del ratón dividido verticalmente del sistema cuando el usuario pasa por encima del nodo. En Windows, es lo mismo que CURSOR_VSIZE.
CURSOR_HSPLIT = 15 --- Muestra el cursor del ratón dividido horizontalmente del sistema cuando el usuario pasa por encima del nodo. En Windows, es lo mismo que CURSOR_HSIZE.
CURSOR_HELP = 16 --- Mostrar el cursor del ratón de ayuda del sistema cuando el usuario pasa por encima del nodo, un signo de interrogación.
enum LayoutPreset:
PRESET_TOP_LEFT = 0 --- Pone las cuatro anclas en la parte superior izquierda de los límites del control parental. Usar con set_anchors_preset.
PRESET_TOP_RIGHT = 1 --- Pone las cuatro anclas en la parte superior derecha de los límites del control parental. Usar con set_anchors_preset.
PRESET_BOTTOM_LEFT = 2 --- Pone las cuatro anclas en la parte inferior izquierda de los límites del control parental. Usar con set_anchors_preset.
PRESET_BOTTOM_RIGHT = 3 --- Pone las cuatro anclas en la parte inferior derecha de los límites del control parental. Usar con set_anchors_preset.
PRESET_CENTER_LEFT = 4 --- Pone las 4 anclas en el centro del borde izquierdo de los límites del control parental. Usar con set_anchors_preset.
PRESET_CENTER_TOP = 5 --- Pone las 4 anclas en el centro del borde superior de los límites del control parental. Usar con set_anchors_preset.
PRESET_CENTER_RIGHT = 6 --- Pone las 4 anclas en el centro del borde derecho de los límites del control parental. Usar con set_anchors_preset.
PRESET_CENTER_BOTTOM = 7 --- Pone las 4 anclas en el centro del borde inferior de los límites del control parental. Usar con set_anchors_preset.
PRESET_CENTER = 8 --- Pone las cuatro anclas en el centro de los límites del control parental. Usar con set_anchors_preset.
PRESET_LEFT_WIDE = 9 --- Pone las 4 anclas en el borde izquierdo del control parental. El margen izquierdo se convierte en relativo al borde izquierdo y el margen superior en relativo a la esquina superior izquierda del nodo padre. Usar con set_anchors_preset.
PRESET_TOP_WIDE = 10 --- Pone las 4 anclas en el borde superior del control parental. El margen izquierdo se convierte en relativo a la esquina superior izquierda, el margen superior relativo al borde superior, y el margen derecho relativo a la esquina superior derecha del nodo padre. Usar con set_anchors_preset.
PRESET_RIGHT_WIDE = 11 --- Pone las 4 anclas en el borde derecho del control parental. El margen derecho se convierte en relativo al borde derecho y el margen superior en relativo a la esquina superior derecha del nodo padre. Usar con set_anchors_preset.
PRESET_BOTTOM_WIDE = 12 --- Pone las 4 anclas en el borde inferior del control parental. El margen izquierdo se convierte en relativo a la esquina inferior izquierda, el margen inferior relativo al borde inferior, y el margen derecho relativo a la esquina inferior derecha del nodo padre. Usar con set_anchors_preset.
PRESET_VCENTER_WIDE = 13 --- Pone las 4 anclas en una línea vertical que corta el control parental por la mitad. Usar con set_anchors_preset.
PRESET_HCENTER_WIDE = 14 --- Pone las 4 anclas en una línea horizontal que corta el control parental por la mitad. Usar con set_anchors_preset.
PRESET_WIDE = 15 --- Pone las 4 anclas en las respectivas esquinas del control parental. Ponga los 4 márgenes a 0 después de aplicar este preajuste y el
Control
se ajustará a su control de padres. Esto equivale a la opción de diseño "Full Rect" del editor. Utilícela con set_anchors_preset.
enum LayoutPresetMode:
PRESET_MODE_MINSIZE = 0 --- El control será redimensionado a su tamaño mínimo.
PRESET_MODE_KEEP_WIDTH = 1 --- El ancho del control no cambiará.
PRESET_MODE_KEEP_HEIGHT = 2 --- La altura del control no cambiará.
PRESET_MODE_KEEP_SIZE = 3 --- El tamaño del control no cambiará.
enum SizeFlags:
SIZE_FILL = 1 --- Le dice al padre Container que expanda los límites de este nodo para llenar todo el espacio disponible sin empujar ningún otro nodo. Usar con size_flags_horizontal y size_flags_vertical.
SIZE_EXPAND = 2 --- Le dice al padre Container que deje que este nodo tome todo el espacio disponible en el eje que marque. Si varios nodos vecinos están configurados para expandirse, compartirán el espacio basado en su relación de estiramiento. Ver size_flags_stretch_ratio. Utilízalo con size_flags_horizontal y size_flags_vertical.
SIZE_EXPAND_FILL = 3 --- Establece las flags de tamaño del nodo para que se llenen y se expandan. Vea las 2 constantes anteriores para más información.
SIZE_SHRINK_CENTER = 4 --- Le dice al padre Container que centre el nodo en sí mismo. Centra el control basado en su caja delimitadora, por lo que no funciona con las flags de tamaño de relleno o expansión. Úsalo con size_flags_horizontal y size_flags_vertical.
SIZE_SHRINK_END = 8 --- Le dice al padre Container que alinee el nodo con su extremo, ya sea el inferior o el derecho. No funciona con las flags de tamaño de relleno o expansión. Úsalo con size_flags_horizontal y size_flags_vertical.
enum MouseFilter:
MOUSE_FILTER_STOP = 0 --- El control recibirá los eventos de entrada del botón del ratón a través del _gui_input si se hace clic en él. Y el control recibirá las señales mouse_entered y mouse_exited. Estos eventos se marcan automáticamente como manejados, y no se propagarán más a otros controles. Esto también resulta en el bloqueo de señales en otros controles.
MOUSE_FILTER_PASS = 1 --- El control recibirá los eventos de entrada del botón del ratón a través del _gui_input si se hace clic en él. Y el control recibirá las señales mouse_entered y mouse_exited. Si este control no maneja el evento, se considerará el control padre (si lo hay), y así sucesivamente hasta que no haya más control padre para manejarlo potencialmente. Esto también permite que las señales se disparen en otros controles. Incluso si ningún control lo maneja, el evento será manejado automáticamente, por lo que las entradas no manejadas no se dispararán.
MOUSE_FILTER_IGNORE = 2 --- El control no recibirá eventos de entrada del botón del ratón a través del _gui_input. El control tampoco recibirá las señales mouse_entered ni mouse_exited. Esto no bloqueará a otros controles para que no reciban estos eventos o para que no disparen las señales. Los eventos ignorados no se manejarán automáticamente.
enum GrowDirection:
GROW_DIRECTION_BEGIN = 0 --- El control crecerá hacia la izquierda o hacia arriba para compensar si su tamaño mínimo se cambia para que sea mayor que su tamaño actual en el eje respectivo.
GROW_DIRECTION_END = 1 --- El control crecerá hacia la derecha o hacia abajo para compensar si su tamaño mínimo se cambia para que sea mayor que su tamaño actual en el eje respectivo.
GROW_DIRECTION_BOTH = 2 --- El control crecerá en ambas direcciones por igual para compensar si su tamaño mínimo se cambia para que sea mayor que su tamaño actual.
enum Anchor:
ANCHOR_BEGIN = 0 --- Encaja uno de los 4 lados del ancla en el origen del nodo
Rect
, en la parte superior izquierda. Úsalo con una de las variables miembroanchor_*
, como anchor_left. Para cambiar las 4 anclas a la vez, usa set_anchors_preset.ANCHOR_END = 1 --- Pone uno de los 4 lados del ancla al final del nodo
Rect
, en la parte inferior derecha. Úsalo con una de las variables miembrosanchor_*
, como anchor_left. Para cambiar las 4 anclas a la vez, usa set_anchors_preset.
Constantes¶
NOTIFICATION_RESIZED = 40 --- Enviado cuando el nodo cambia de tamaño. Usa rect_size para obtener el nuevo tamaño.
NOTIFICATION_MOUSE_ENTER = 41 --- Se envía cuando el puntero del ratón entra en el nodo.
NOTIFICATION_MOUSE_EXIT = 42 --- Se envía cuando el puntero del ratón sale del nodo.
NOTIFICATION_FOCUS_ENTER = 43 --- Enviado cuando el nodo agarra el foco.
NOTIFICATION_FOCUS_EXIT = 44 --- Enviado cuando el nodo pierde el enfoque.
NOTIFICATION_THEME_CHANGED = 45 --- Sent when the node's theme changes, right before Godot redraws the control. Happens when you call one of the
add_*_override
methods.NOTIFICATION_MODAL_CLOSE = 46 --- Sent when an open modal dialog closes. See show_modal.
NOTIFICATION_SCROLL_BEGIN = 47 --- Enviado cuando este nodo está dentro de un ScrollContainer que ha comenzado a ser desplazado.
NOTIFICATION_SCROLL_END = 48 --- Enviado cuando este nodo está dentro de un ScrollContainer que ha dejado de ser desplazado.
Descripciones de Propiedades¶
float anchor_bottom
Default |
|
Getter |
get_anchor() |
Ancla el borde inferior del nodo al origen, el centro o el final de su control parental. Cambia la forma en que el margen inferior se actualiza cuando el nodo se mueve o cambia de tamaño. Puedes usar una de las constantes Anchor por conveniencia.
float anchor_left
Default |
|
Getter |
get_anchor() |
Ancla el borde izquierdo del nodo al origen, el centro o el final de su control parental. Cambia la forma en que el margen izquierdo se actualiza cuando el nodo se mueve o cambia de tamaño. Puedes usar una de las constantes Anchor por conveniencia.
float anchor_right
Default |
|
Getter |
get_anchor() |
Ancla el borde derecho del nodo al origen, el centro o el final de su control parental. Cambia la forma en que el margen derecho se actualiza cuando el nodo se mueve o cambia de tamaño. Puedes usar una de las constantes Anchor por conveniencia.
float anchor_top
Default |
|
Getter |
get_anchor() |
Anchors the top edge of the node to the origin, the center or the end of its parent control. It changes how the top margin updates when the node moves or changes size. You can use one of the Anchor constants for convenience.
FocusMode focus_mode
Default |
|
Setter |
set_focus_mode(value) |
Getter |
get_focus_mode() |
El modo de acceso de enfoque para el control (Ninguno, Clic o Todos). Sólo un Control puede ser enfocado al mismo tiempo, y recibirá señales del teclado.
NodePath focus_neighbour_bottom
Default |
|
Setter |
set_focus_neighbour(value) |
Getter |
get_focus_neighbour() |
Le dice a Godot a qué nodo debe darle enfoque de teclado si el usuario presiona la flecha hacia abajo en el teclado o hacia abajo en un gamepad por defecto. Puede cambiar la tecla editando la acción de entrada ui_down
. El nodo debe ser un Control
. Si no se establece esta propiedad, Godot dará el foco al Control
más cercano a la parte inferior de éste.
NodePath focus_neighbour_left
Default |
|
Setter |
set_focus_neighbour(value) |
Getter |
get_focus_neighbour() |
Le dice a Godot a qué nodo debe dar enfoque de teclado si el usuario presiona la flecha izquierda en el teclado o la izquierda en un gamepad por defecto. Puede cambiar la tecla editando la acción de entrada ui_left
. El nodo debe ser un Control
. Si no se establece esta propiedad, Godot dará el foco al Control
más cercano a la izquierda de éste.
NodePath focus_neighbour_right
Default |
|
Setter |
set_focus_neighbour(value) |
Getter |
get_focus_neighbour() |
Tells Godot which node it should give keyboard focus to if the user presses the right arrow on the keyboard or right on a gamepad by default. You can change the key by editing the ui_right
input action. The node must be a Control
. If this property is not set, Godot will give focus to the closest Control
to the bottom of this one.
NodePath focus_neighbour_top
Default |
|
Setter |
set_focus_neighbour(value) |
Getter |
get_focus_neighbour() |
Le dice a Godot a qué nodo debe darle enfoque de teclado si el usuario presiona la flecha superior del teclado o el arriba de un gamepad por defecto. Puede cambiar la tecla editando la acción de entrada ui_top
. El nodo debe ser un Control
. Si no se establece esta propiedad, Godot dará el foco al Control
más cercano a la parte inferior de éste.
NodePath focus_next
Default |
|
Setter |
set_focus_next(value) |
Getter |
get_focus_next() |
Tells Godot which node it should give keyboard focus to if the user presses Tab on a keyboard by default. You can change the key by editing the ui_focus_next
input action.
If this property is not set, Godot will select a "best guess" based on surrounding nodes in the scene tree.
NodePath focus_previous
Default |
|
Setter |
set_focus_previous(value) |
Getter |
get_focus_previous() |
Tells Godot which node it should give keyboard focus to if the user presses Shift+Tab on a keyboard by default. You can change the key by editing the ui_focus_prev
input action.
If this property is not set, Godot will select a "best guess" based on surrounding nodes in the scene tree.
GrowDirection grow_horizontal
Default |
|
Setter |
set_h_grow_direction(value) |
Getter |
get_h_grow_direction() |
Controla la dirección en el eje horizontal en la que el control debe crecer si su tamaño mínimo horizontal se cambia para que sea mayor que su tamaño actual, ya que el control siempre tiene que ser al menos del tamaño mínimo.
GrowDirection grow_vertical
Default |
|
Setter |
set_v_grow_direction(value) |
Getter |
get_v_grow_direction() |
Controla la dirección en el eje vertical en la que el control debe crecer si su tamaño mínimo vertical se cambia para que sea mayor que su tamaño actual, ya que el control siempre tiene que ser al menos del tamaño mínimo.
String hint_tooltip
Default |
|
Setter |
set_tooltip(value) |
Changes the tooltip text. The tooltip appears when the user's mouse cursor stays idle over this control for a few moments, provided that the mouse_filter property is not MOUSE_FILTER_IGNORE. You can change the time required for the tooltip to appear with gui/timers/tooltip_delay_sec
option in Project Settings.
The tooltip popup will use either a default implementation, or a custom one that you can provide by overriding _make_custom_tooltip. The default tooltip includes a PopupPanel and Label whose theme properties can be customized using Theme methods with the "TooltipPanel"
and "TooltipLabel"
respectively. For example:
var style_box = StyleBoxFlat.new()
style_box.set_bg_color(Color(1, 1, 0))
style_box.set_border_width_all(2)
# We assume here that the `theme` property has been assigned a custom Theme beforehand.
theme.set_stylebox("panel", "TooltipPanel", style_box)
theme.set_color("font_color", "TooltipLabel", Color(0, 1, 1))
bool input_pass_on_modal_close_click
Default |
|
Setter |
set_pass_on_modal_close_click(value) |
Getter |
get_pass_on_modal_close_click() |
Enables whether input should propagate when you close the control as modal.
If false
, stops event handling at the viewport input event handling. The viewport first hides the modal and after marks the input as handled.
float margin_bottom
Default |
|
Setter |
set_margin(value) |
Getter |
get_margin() |
Distancia entre el borde inferior del nodo y su control padre, basado en anchor_bottom.
Los márgenes suelen estar controlados por uno o varios nodos padre Container, por lo que no debe modificarlos manualmente si su nodo es hijo directo de un Container. Los márgenes se actualizan automáticamente cuando mueve o cambia el tamaño del nodo.
float margin_left
Default |
|
Setter |
set_margin(value) |
Getter |
get_margin() |
Distancia entre el borde izquierdo del nodo y su control padre, basado en anchor_left.
Los márgenes suelen estar controlados por uno o varios nodos padre Container, por lo que no debe modificarlos manualmente si su nodo es hijo directo de un Container. Los márgenes se actualizan automáticamente cuando mueve o cambia el tamaño del nodo.
float margin_right
Default |
|
Setter |
set_margin(value) |
Getter |
get_margin() |
Distancia entre el borde derecho del nodo y su control padre, basado en anchor_right.
Los márgenes suelen estar controlados por uno o varios nodos padre Container, por lo que no debe modificarlos manualmente si su nodo es hijo directo de un Container. Los márgenes se actualizan automáticamente cuando mueve o cambia el tamaño del nodo.
float margin_top
Default |
|
Setter |
set_margin(value) |
Getter |
get_margin() |
Distancia entre el borde superior del nodo y su control padre, basado en anchor_top.
Los márgenes suelen estar controlados por uno o varios nodos padre Container, por lo que no debe modificarlos manualmente si su nodo es hijo directo de un Container. Los márgenes se actualizan automáticamente cuando mueve o cambia el tamaño del nodo.
CursorShape mouse_default_cursor_shape
Default |
|
Setter |
set_default_cursor_shape(value) |
Getter |
get_default_cursor_shape() |
La forma del cursor por defecto para este control. Útil para los plugins de Godot y las aplicaciones o juegos que utilizan los cursores del ratón del sistema.
Nota: En Linux, las formas pueden variar dependiendo del tema del cursor del sistema.
MouseFilter mouse_filter
Default |
|
Setter |
set_mouse_filter(value) |
Getter |
get_mouse_filter() |
Controla si el control será capaz de recibir eventos de entrada del botón del ratón a través del _gui_input y cómo estos eventos deben ser manejados. También controla si el control puede recibir las señales mouse_entered, y mouse_exited. Mira las constantes para aprender lo que hace cada una.
bool rect_clip_content
Default |
|
Setter |
set_clip_contents(value) |
Getter |
is_clipping_contents() |
Permite si la representación de los hijos basados en CanvasItem debe ser recortada al rectángulo de este control. Si true
, no se renderizarán las partes de un hijo que estarían visiblemente fuera del rectángulo de este control.
Vector2 rect_global_position
Getter |
get_global_position() |
La posición global del nodo, en relación con el mundo (normalmente en la esquina superior izquierda de la ventana).
Vector2 rect_min_size
Default |
|
Setter |
set_custom_minimum_size(value) |
Getter |
get_custom_minimum_size() |
El tamaño mínimo del rectángulo delimitador del nodo. Si lo fijas en un valor mayor que (0, 0), el rectángulo delimitador del nodo siempre tendrá al menos este tamaño, aunque su contenido sea menor. Si se establece en (0, 0), el nodo se dimensiona automáticamente para ajustarse a su contenido, ya sea una textura o un nodo hijo.
Vector2 rect_pivot_offset
Default |
|
Setter |
set_pivot_offset(value) |
Getter |
get_pivot_offset() |
Por defecto, el pivote del nodo es su esquina superior izquierda. Cuando cambias su rect_scale, se escalará alrededor de este pivote. Establezca esta propiedad en rect_size / 2 para centrar el pivote en el rectángulo del nodo.
Vector2 rect_position
Default |
|
Getter |
get_position() |
La posición del nodo, en relación con su padre. Corresponde a la esquina superior izquierda del rectángulo. La propiedad no se ve afectada por rect_pivot_offset.
float rect_rotation
Default |
|
Setter |
set_rotation_degrees(value) |
Getter |
get_rotation_degrees() |
La rotación del nodo alrededor de su pivote, en grados. Ver rect_pivot_offset para cambiar la posición del pivote.
Vector2 rect_scale
Default |
|
Setter |
set_scale(value) |
Getter |
get_scale() |
The node's scale, relative to its rect_size. Change this property to scale the node around its rect_pivot_offset. The Control's hint_tooltip will also scale according to this value.
Note: This property is mainly intended to be used for animation purposes. Text inside the Control will look pixelated or blurry when the Control is scaled. To support multiple resolutions in your project, use an appropriate viewport stretch mode as described in the documentation instead of scaling Controls individually.
Note: If the Control node is a child of a Container node, the scale will be reset to Vector2(1, 1)
when the scene is instanced. To set the Control's scale when it's instanced, wait for one frame using yield(get_tree(), "idle_frame")
then set its rect_scale property.
Vector2 rect_size
Default |
|
Getter |
get_size() |
El tamaño del rectángulo delimitador del nodo, en píxeles. Los nodos Container actualizan esta propiedad automáticamente.
int size_flags_horizontal
Default |
|
Setter |
set_h_size_flags(value) |
Getter |
get_h_size_flags() |
Le dice a los nodos padre Container cómo deben cambiar de tamaño y colocar el nodo en el eje X. Usa una de las constantes SizeFlags para cambiar los flags. Vea las constantes para aprender lo que hace cada una.
float size_flags_stretch_ratio
Default |
|
Setter |
set_stretch_ratio(value) |
Getter |
get_stretch_ratio() |
Si el nodo y al menos uno de sus vecinos utiliza el flag de tamaño SIZE_EXPAND, el padre Container le dejará ocupar más o menos espacio dependiendo de esta propiedad. Si este nodo tiene un ratio de estiramiento de 2 y su vecino un ratio de 1, este nodo tomará dos tercios del espacio disponible.
int size_flags_vertical
Default |
|
Setter |
set_v_size_flags(value) |
Getter |
get_v_size_flags() |
Le dice a los nodos padres Container cómo deben cambiar de tamaño y colocar el nodo en el eje Y. Usa una de las constantes SizeFlags para cambiar los flags. Vea las constantes para aprender lo que hace cada una.
Theme theme
Setter |
set_theme(value) |
Getter |
get_theme() |
Cambiar esta propiedad reemplaza el actual recurso Theme que este nodo y todos sus hijos Control
utilizan.
Descripciones de Métodos¶
bool _clips_input ( ) virtual
Método virtual a ser implementado por el usuario. Devuelve si _gui_input no debe ser llamado para los controles hijos fuera del rectángulo de este control. La entrada será recortada al rectángulo de este Control
. Similar a rect_clip_content, pero no afecta a la visibilidad.
Si no se anula, el valor por defecto es false
.
Vector2 _get_minimum_size ( ) virtual
Virtual method to be implemented by the user. Returns the minimum size for this control. Alternative to rect_min_size for controlling minimum size via code. The actual minimum size will be the max value of these two (in each axis separately).
If not overridden, defaults to Vector2.ZERO.
Note: This method will not be called when the script is attached to a Control
node that already overrides its minimum size (e.g. Label, Button, PanelContainer etc.). It can only be used with most basic GUI nodes, like Control
, Container, Panel etc.
void _gui_input ( InputEvent event ) virtual
Virtual method to be implemented by the user. Use this method to process and accept inputs on UI elements. See accept_event.
Example: clicking a control.
func _gui_input(event):
if event is InputEventMouseButton:
if event.button_index == BUTTON_LEFT and event.pressed:
print("I've been clicked D:")
The event won't trigger if:
* clicking outside the control (see has_point);
* control has mouse_filter set to MOUSE_FILTER_IGNORE;
* control is obstructed by another Control
on top of it, which doesn't have mouse_filter set to MOUSE_FILTER_IGNORE;
* control's parent has mouse_filter set to MOUSE_FILTER_STOP or has accepted the event;
* it happens outside the parent's rectangle and the parent has either rect_clip_content or _clips_input enabled.
Note: Event position is relative to the control origin.
Virtual method to be implemented by the user. Returns a Control
node that should be used as a tooltip instead of the default one. The for_text
includes the contents of the hint_tooltip property.
The returned node must be of type Control
or Control-derived. It can have child nodes of any type. It is freed when the tooltip disappears, so make sure you always provide a new instance (if you want to use a pre-existing node from your scene tree, you can duplicate it and pass the duplicated instance). When null
or a non-Control node is returned, the default tooltip will be used instead.
The returned node will be added as child to a PopupPanel, so you should only provide the contents of that panel. That PopupPanel can be themed using Theme.set_stylebox for the type "TooltipPanel"
(see hint_tooltip for an example).
Note: The tooltip is shrunk to minimal size. If you want to ensure it's fully visible, you might want to set its rect_min_size to some non-zero value.
Example of usage with a custom-constructed node:
func _make_custom_tooltip(for_text):
var label = Label.new()
label.text = for_text
return label
Example of usage with a custom scene instance:
func _make_custom_tooltip(for_text):
var tooltip = preload("res://SomeTooltipScene.tscn").instance()
tooltip.get_node("Label").text = for_text
return tooltip
void accept_event ( )
Marca un evento de entrada como manejado. Una vez que aceptas un evento de entrada, deja de propagarse, incluso a los nodos que escuchan Node._unhandled_input o Node._unhandled_key_input.
Creates a local override for a theme Color with the specified name
. Local overrides always take precedence when fetching theme items for the control. An override cannot be removed, but it can be overridden with the corresponding default value.
See also get_color.
Example of overriding a label's color and resetting it later:
# Given the child Label node "MyLabel", override its font color with a custom value.
$MyLabel.add_color_override("font_color", Color(1, 0.5, 0))
# Reset the font color of the child label.
$MyLabel.add_color_override("font_color", get_color("font_color", "Label"))
Creates a local override for a theme constant with the specified name
. Local overrides always take precedence when fetching theme items for the control. An override cannot be removed, but it can be overridden with the corresponding default value.
See also get_constant.
Creates a local override for a theme Font with the specified name
. Local overrides always take precedence when fetching theme items for the control. An override can be removed by assigning it a null
value.
See also get_font.
Creates a local override for a theme icon with the specified name
. Local overrides always take precedence when fetching theme items for the control. An override can be removed by assigning it a null
value.
See also get_icon.
Creates a local override for a theme shader with the specified name
. Local overrides always take precedence when fetching theme items for the control. An override can be removed by assigning it a null
value.
Creates a local override for a theme StyleBox with the specified name
. Local overrides always take precedence when fetching theme items for the control. An override can be removed by assigning it a null
value.
See also get_stylebox.
Example of modifying a property in a StyleBox by duplicating it:
# The snippet below assumes the child node MyButton has a StyleBoxFlat assigned.
# Resources are shared across instances, so we need to duplicate it
# to avoid modifying the appearance of all other buttons.
var new_stylebox_normal = $MyButton.get_stylebox("normal").duplicate()
new_stylebox_normal.border_width_top = 3
new_stylebox_normal.border_color = Color(0, 1, 0.5)
$MyButton.add_stylebox_override("normal", new_stylebox_normal)
# Remove the stylebox override.
$MyButton.add_stylebox_override("normal", null)
Godot llama a este método para probar si data
de un control get_drag_data puede ser lanzado en position
. position
es local a este control.
Este método sólo debe usarse para probar los datos. Procesa los datos en drop_data.
func can_drop_data(position, data):
# Cheque la posición is es relevante para ti
# De otra forma solo chequea los datos
return typeof(data) == TYPE_DICTIONARY and data.has("esperado")
Godot llama a este método para pasarle el data
del resultado del get_drag_data de un control. Godot primero llama a can_drop_data para probar si data
puede caer en position
donde position
es local a este control.
func can_drop_data(position, data):
return typeof(data) == TYPE_DICTIONARY and data.has("color")
func drop_data(position, data):
color = data["color"]
Control find_next_valid_focus ( ) const
Finds the next (below in the tree) Control
that can receive the focus.
Control find_prev_valid_focus ( ) const
Finds the previous (above in the tree) Control
that can receive the focus.
Fuerza el arrastre y desvía get_drag_data y set_drag_preview pasando data
y preview
. El arrastre se iniciará incluso si el ratón no está encima ni presionado en este control.
Los métodos can_drop_data y drop_data deben ser implementados en los controles que quieran recibir datos de arrastre.
Devuelve el ancla identificada por la constante margin
de enum Margin. Un método de obtención para anchor_bottom, anchor_left, anchor_right y anchor_top.
Vector2 get_begin ( ) const
Devuelve margin_left y margin_top. Véase también rect_position.
Returns a Color from the first matching Theme in the tree if that Theme has a color item with the specified name
and theme_type
. If theme_type
is omitted the class name of the current control is used as the type. If the type is a class name its parent classes are also checked, in order of inheritance.
For the current control its local overrides are considered first (see add_color_override), then its assigned theme. After the current control, each parent control and its assigned theme are considered; controls without a theme assigned are skipped. If no matching Theme is found in the tree, a custom project Theme (see ProjectSettings.gui/theme/custom) and the default Theme are used.
func _ready():
# Get the font color defined for the current Control's class, if it exists.
modulate = get_color("font_color")
# Get the font color defined for the Button class.
modulate = get_color("font_color", "Button")
Vector2 get_combined_minimum_size ( ) const
Devuelve el tamaño mínimo combinado de rect_min_size y get_minimum_size.
Returns a constant from the first matching Theme in the tree if that Theme has a constant item with the specified name
and theme_type
.
See get_color for details.
CursorShape get_cursor_shape ( Vector2 position=Vector2( 0, 0 ) ) const
Devuelve la forma del cursor del ratón que el control muestra al pasar el ratón por encima. Ver CursorShape.
Godot llama a este método para obtener datos que pueden ser arrastrados y soltados en los controles que esperan datos de caída. Devuelve null
si no hay datos que arrastrar. Los controles que quieran recibir datos de arrastre deben implementar can_drop_data y drop_data. position
es local para este control. El arrastre puede ser forzado con force_drag.
Una vista previa que seguirá al ratón que debe representar los datos se puede fijar con set_drag_preview. Un buen momento para establecer la vista previa es en este método.
func get_drag_data(position):
var misdatos = fabricar_datos()
set_drag_preview(make_preview(mydata))
return misdatos
Vector2 get_end ( ) const
Devuelve margin_right y margin_bottom.
Devuelve el vecino de enfocado identificado por la constante margin
del enum Margin. Un método de obtención para focus_neighbour_bottom, focus_neighbour_left, focus_neighbour_right y focus_neighbour_top.
Control get_focus_owner ( ) const
Devuelve el control que tiene el foco del teclado o null
si no hay ninguno.
Returns a Font from the first matching Theme in the tree if that Theme has a font item with the specified name
and theme_type
.
See get_color for details.
Rect2 get_global_rect ( ) const
Devuelve la posición y el tamaño del control en relación con la esquina superior izquierda de la pantalla. Ver rect_position y rect_size.
Returns an icon from the first matching Theme in the tree if that Theme has an icon item with the specified name
and theme_type
.
See get_color for details.
Devuelve el ancla identificada por la constante margin
del enum Margin. Un método de obtención para margin_bottom, margin_left, margin_right y margin_top.
Vector2 get_minimum_size ( ) const
Devuelve el tamaño mínimo para este control. Ver rect_min_size.
Vector2 get_parent_area_size ( ) const
Devuelve la anchura/altura ocupada en el control parental.
Control get_parent_control ( ) const
Devuelve el nodo de control del padre.
Rect2 get_rect ( ) const
Devuelve la posición y el tamaño del control en relación con la esquina superior izquierda del control principal. Ver rect_position y rect_size.
float get_rotation ( ) const
Devuelve la rotación (en radianes).
Returns a StyleBox from the first matching Theme in the tree if that Theme has a stylebox item with the specified name
and theme_type
.
See get_color for details.
Font get_theme_default_font ( ) const
Returns the default font from the first matching Theme in the tree if that Theme has a valid Theme.default_font value.
See get_color for details.
Devuelve la sugerencia, que aparecerá cuando el cursor se apoye sobre este control. Ver hint_tooltip.
void grab_click_focus ( )
Crea un InputEventMouseButton que intenta hacer clic en el control. Si se recibe el evento, el control adquiere el enfoque.
func _process(delta):
grab_click_focus() # cuando se hace click otro nodo control, este nodo sera clickado en vez del previo
void grab_focus ( )
Roba el foco de otro control y pasa a ser el control enfocado (ver focus_mode).
Returns true
if there is a matching Theme in the tree that has a color item with the specified name
and theme_type
.
See get_color for details.
Returns true
if there is a local override for a theme Color with the specified name
in this Control
node.
See add_color_override.
Returns true
if there is a matching Theme in the tree that has a constant item with the specified name
and theme_type
.
See get_color for details.
Returns true
if there is a local override for a theme constant with the specified name
in this Control
node.
bool has_focus ( ) const
Devuelve true
si este es el control enfocado actual. Ver focus_mode.
Returns true
if there is a matching Theme in the tree that has a font item with the specified name
and theme_type
.
See get_color for details.
Returns true
if there is a local override for a theme Font with the specified name
in this Control
node.
See add_font_override.
Returns true
if there is a matching Theme in the tree that has an icon item with the specified name
and theme_type
.
See get_color for details.
Returns true
if there is a local override for a theme icon with the specified name
in this Control
node.
See add_icon_override.
Método virtual a ser implementado por el usuario. Devuelve si el point
dado está dentro de este control.
Si no está sobreescrito, el comportamiento por defecto es comprobar si el punto está dentro del Rectángulo del control.
Nota: Si quieres comprobar si un punto está dentro del control, puedes usar get_rect().has_point(point)
.
Returns true
if there is a local override for a theme shader with the specified name
in this Control
node.
See add_shader_override.
Returns true
if there is a matching Theme in the tree that has a stylebox item with the specified name
and theme_type
.
See get_color for details.
Returns true
if there is a local override for a theme StyleBox with the specified name
in this Control
node.
void minimum_size_changed ( )
Invalida el tamaño de la memoria caché en este nodo y en los nodos padres hasta el nivel superior. Está pensado para ser usado con get_minimum_size cuando se cambia el valor de retorno. Si se establece rect_min_size se llama directamente a este método de forma automática.
void release_focus ( )
Deje el enfoque. Ningún otro control podrá recibir la entrada del teclado.
void set_anchor ( Margin margin, float anchor, bool keep_margin=false, bool push_opposite_anchor=true )
Establece el ancla identificada por la constante margin
del enum Margin al valor anchor
. Un método de fijación para anchor_bottom, anchor_left, anchor_right y anchor_top.
Si keep_margin
es true
, los márgenes no se actualizan después de esta operación.
Si push_opposite_anchor
es true
y el ancla opuesta se superpone a esta ancla, la opuesta tendrá su valor sobreescrito. Por ejemplo, cuando se ajusta el ancla izquierda a 1 y el ancla derecha tiene el valor de 0,5, el ancla derecha también obtendrá el valor de 1. Si push_opposite_anchor
fuera false
, el ancla izquierda obtendría el valor 0,5.
void set_anchor_and_margin ( Margin margin, float anchor, float offset, bool push_opposite_anchor=false )
Funciona igual que set_anchor, pero en lugar del argumento keep_margin
y la actualización automática del margen, permite establecer el desplazamiento del margen por sí mismo (ver set_margin).
void set_anchors_and_margins_preset ( LayoutPreset preset, LayoutPresetMode resize_mode=0, int margin=0 )
Establece tanto la preselección del ancla como la preselección del margen. Ver set_anchors_preset y set_margins_preset.
void set_anchors_preset ( LayoutPreset preset, bool keep_margins=false )
Sets the anchors to a preset
from LayoutPreset enum. This is the code equivalent to using the Layout menu in the 2D editor.
If keep_margins
is true
, control's position will also be updated.
void set_begin ( Vector2 position )
Establece margin_left y margin_top al mismo tiempo. Equivale a cambiar rect_position.
void set_drag_forwarding ( Control target )
Adelanta el manejo del arrastre y suelta de este control al control de target
.
El reenvío puede ser implementado en el control de destino de manera similar a los métodos get_drag_data, can_drop_data, y drop_data pero con dos diferencias:
El nombre de la función debe ser sufijado con _fw
La función debe tener un argumento extra que es el control que hace el reenvío
# EsteControl.gd
extends Control
func _ready():
set_drag_forwarding(control_objetivo)
# ControlObjetivo.gd
extends Control
func puede_arrastrar_datos_fw(posicion, datos, desde_control):
return true
func arrastra_datos_fw(posicion, datos, desde_control):
mi_manejo_de_datos(data)
func obtener_datos_arrastrados_fw(posicion, datos, desde_control):
set_drag_preview(mi_prevista)
return misdatos()
void set_drag_preview ( Control control )
Shows the given control at the mouse pointer. A good time to call this method is in get_drag_data. The control must not be in the scene tree. You should not free the control, and you should not keep a reference to the control beyond the duration of the drag. It will be deleted automatically after the drag has ended.
export (Color, RGBA) var color = Color(1, 0, 0, 1)
func get_drag_data(position):
# Use a control that is not in the tree
var cpb = ColorPickerButton.new()
cpb.color = color
cpb.rect_size = Vector2(50, 50)
set_drag_preview(cpb)
return color
void set_end ( Vector2 position )
Establece margin_right y margin_bottom al mismo tiempo.
Establece el ancla identificada por la constante margin
desde el Margin hasta Control
en la ruta del nodo neighbour
. Un método de fijación para focus_neighbour_bottom, focus_neighbour_left, focus_neighbour_right y focus_neighbour_top.
Establece el rect_global_position a la position
dada.
Si keep_margins
es true
, los anclajes del control se actualizarán en lugar de los márgenes.
Establece el margen identificado por margin
constante desde el enum Margin hasta determinado offset
. Un método de fijación para margin_bottom, margin_left, margin_right y margin_top.
void set_margins_preset ( LayoutPreset preset, LayoutPresetMode resize_mode=0, int margin=0 )
Sets the margins to a preset
from LayoutPreset enum. This is the code equivalent to using the Layout menu in the 2D editor.
Use parameter resize_mode
with constants from LayoutPresetMode to better determine the resulting size of the Control
. Constant size will be ignored if used with presets that change size, e.g. PRESET_LEFT_WIDE
.
Use parameter margin
to determine the gap between the Control
and the edges.
Establece la rect_position a la position
dada.
Si keep_margins
es true
, los anclajes del control se actualizarán en lugar de los márgenes.
void set_rotation ( float radians )
Establece la rotación (en radianes).
Establece el tamaño (ver rect_size).
Si keep_margins
es true
, los anclajes del control se actualizarán en lugar de los márgenes.
void show_modal ( bool exclusive=false )
Displays a control as modal. Control must be a subwindow. Modal controls capture the input signals until closed or the area outside them is accessed. When a modal control loses focus, or the ESC key is pressed, they automatically hide. Modal controls are used extensively for popup dialogs and menus.
If exclusive
is true
, other controls will not receive input and clicking outside this control will not close it.
void warp_mouse ( Vector2 to_position )
Mueve el cursor del ratón a to_position
, relativo a la rect_position de este Control
.