Widget#
Superclasses: InitiallyUnowned
, Object
Subclasses: ActionBar
, AppChooserButton
, AppChooserWidget
, AspectFrame
, Box
, Button
, Calendar
, CellView
, CenterBox
, CheckButton
, ColorButton
, ColorChooserWidget
, ColorDialogButton
, ColumnView
, ComboBox
, DragIcon
, DrawingArea
, DropDown
, EditableLabel
, Entry
, Expander
, FileChooserWidget
, Fixed
, FlowBox
, FlowBoxChild
, FontButton
, FontChooserWidget
, FontDialogButton
, Frame
, GLArea
, GraphicsOffload
, Grid
, HeaderBar
, IconView
, Image
, InfoBar
, Inscription
, Label
, LevelBar
, ListBase
, ListBox
, ListBoxRow
, MediaControls
, MenuButton
, Notebook
, Overlay
, Paned
, PasswordEntry
, Picture
, Popover
, PopoverMenuBar
, ProgressBar
, Range
, Revealer
, ScaleButton
, Scrollbar
, ScrolledWindow
, SearchBar
, SearchEntry
, Separator
, ShortcutLabel
, ShortcutsShortcut
, SpinButton
, Spinner
, Stack
, StackSidebar
, StackSwitcher
, Statusbar
, Switch
, Text
, TextView
, TreeExpander
, TreeView
, Video
, Viewport
, Window
, WindowControls
, WindowHandle
Implemented Interfaces: Accessible
, Buildable
, ConstraintTarget
The base class for all widgets.
GtkWidget
is the base class all widgets in GTK derive from. It manages the
widget lifecycle, layout, states and style.
Height-for-width Geometry Management#
GTK uses a height-for-width (and width-for-height) geometry management system. Height-for-width means that a widget can change how much vertical space it needs, depending on the amount of horizontal space that it is given (and similar for width-for-height). The most common example is a label that reflows to fill up the available width, wraps to fewer lines, and therefore needs less height.
Height-for-width geometry management is implemented in GTK by way of two virtual methods:
There are some important things to keep in mind when implementing height-for-width and when using it in widget implementations.
If you implement a direct GtkWidget
subclass that supports
height-for-width or width-for-height geometry management for itself
or its child widgets, the get_request_mode
virtual
function must be implemented as well and return the widget’s preferred
request mode. The default implementation of this virtual function
returns CONSTANT_SIZE
, which means that the widget will
only ever get -1 passed as the for_size value to its
measure
implementation.
The geometry management system will query a widget hierarchy in
only one orientation at a time. When widgets are initially queried
for their minimum sizes it is generally done in two initial passes
in the SizeRequestMode
chosen by the toplevel.
For example, when queried in the normal HEIGHT_FOR_WIDTH
mode:
First, the default minimum and natural width for each widget
in the interface will be computed using measure
with an
orientation of HORIZONTAL
and a for_size of -1.
Because the preferred widths for each widget depend on the preferred
widths of their children, this information propagates up the hierarchy,
and finally a minimum and natural width is determined for the entire
toplevel. Next, the toplevel will use the minimum width to query for the
minimum height contextual to that width using measure
with an
orientation of VERTICAL
and a for_size of the just computed
width. This will also be a highly recursive operation. The minimum height
for the minimum width is normally used to set the minimum size constraint
on the toplevel.
After the toplevel window has initially requested its size in both
dimensions it can go on to allocate itself a reasonable size (or a size
previously specified with set_default_size
). During the
recursive allocation process it’s important to note that request cycles
will be recursively executed while widgets allocate their children.
Each widget, once allocated a size, will go on to first share the
space in one orientation among its children and then request each child’s
height for its target allocated width or its width for allocated height,
depending. In this way a GtkWidget
will typically be requested its size
a number of times before actually being allocated a size. The size a
widget is finally allocated can of course differ from the size it has
requested. For this reason, GtkWidget
caches a small number of results
to avoid re-querying for the same sizes in one allocation cycle.
If a widget does move content around to intelligently use up the
allocated size then it must support the request in both
GtkSizeRequestMode
s even if the widget in question only
trades sizes in a single orientation.
For instance, a Label
that does height-for-width word wrapping
will not expect to have measure
with an orientation of
VERTICAL
called because that call is specific to a
width-for-height request. In this case the label must return the height
required for its own minimum possible width. By following this rule any
widget that handles height-for-width or width-for-height requests will
always be allocated at least enough space to fit its own content.
Here are some examples of how a HEIGHT_FOR_WIDTH
widget
generally deals with width-for-height requests:
static void
foo_widget_measure (GtkWidget *widget,
GtkOrientation orientation,
int for_size,
int *minimum_size,
int *natural_size,
int *minimum_baseline,
int *natural_baseline)
{
if (orientation == GTK_ORIENTATION_HORIZONTAL)
{
// Calculate minimum and natural width
}
else // VERTICAL
{
if (i_am_in_height_for_width_mode)
{
int min_width, dummy;
// First, get the minimum width of our widget
GTK_WIDGET_GET_CLASS (widget)->measure (widget, GTK_ORIENTATION_HORIZONTAL, -1,
&min_width, &dummy, &dummy, &dummy);
// Now use the minimum width to retrieve the minimum and natural height to display
// that width.
GTK_WIDGET_GET_CLASS (widget)->measure (widget, GTK_ORIENTATION_VERTICAL, min_width,
minimum_size, natural_size, &dummy, &dummy);
}
else
{
// ... some widgets do both.
}
}
}
Often a widget needs to get its own request during size request or allocation. For example, when computing height it may need to also compute width. Or when deciding how to use an allocation, the widget may need to know its natural size. In these cases, the widget should be careful to call its virtual methods directly, like in the code example above.
It will not work to use the wrapper function measure
inside your own size_allocate
implementation.
These return a request adjusted by SizeGroup
, the widget’s
align and expand flags, as well as its CSS style.
If a widget used the wrappers inside its virtual method implementations, then the adjustments (such as widget margins) would be applied twice. GTK therefore does not allow this and will warn if you try to do it.
Of course if you are getting the size request for another widget, such
as a child widget, you must use measure
; otherwise, you
would not properly consider widget margins, SizeGroup
, and
so forth.
GTK also supports baseline vertical alignment of widgets. This means that widgets are positioned such that the typographical baseline of widgets in the same row are aligned. This happens if a widget supports baselines, has a vertical alignment using baselines, and is inside a widget that supports baselines and has a natural “row” that it aligns to the baseline, or a baseline assigned to it by the grandparent.
Baseline alignment support for a widget is also done by the
measure
virtual function. It allows you to report
both a minimum and natural size.
If a widget ends up baseline aligned it will be allocated all the space in
the parent as if it was FILL
, but the selected baseline can be
found via get_baseline
. If the baseline has a
value other than -1 you need to align the widget such that the baseline
appears at the position.
GtkWidget as GtkBuildable#
The GtkWidget
implementation of the GtkBuildable
interface
supports various custom elements to specify additional aspects of widgets
that are not directly expressed as properties.
If the widget uses a LayoutManager
, GtkWidget
supports
a custom <layout>
element, used to define layout properties:
<object class="GtkGrid" id="my_grid">
<child>
<object class="GtkLabel" id="label1">
<property name="label">Description</property>
<layout>
<property name="column">0</property>
<property name="row">0</property>
<property name="row-span">1</property>
<property name="column-span">1</property>
</layout>
</object>
</child>
<child>
<object class="GtkEntry" id="description_entry">
<layout>
<property name="column">1</property>
<property name="row">0</property>
<property name="row-span">1</property>
<property name="column-span">1</property>
</layout>
</object>
</child>
</object>
GtkWidget
allows style information such as style classes to
be associated with widgets, using the custom <style>
element:
<object class="GtkButton" id="button1">
<style>
<class name="my-special-button-class"/>
<class name="dark-button"/>
</style>
</object>
GtkWidget
allows defining accessibility information, such as properties,
relations, and states, using the custom <accessibility>
element:
<object class="GtkButton" id="button1">
<accessibility>
<property name="label">Download</property>
<relation name="labelled-by">label1</relation>
</accessibility>
</object>
Building composite widgets from template XML#
GtkWidget
exposes some facilities to automate the procedure
of creating composite widgets using “templates”.
To create composite widgets with GtkBuilder
XML, one must associate
the interface description with the widget class at class initialization
time using set_template
.
The interface description semantics expected in composite template descriptions
is slightly different from regular Builder
XML.
Unlike regular interface descriptions, set_template
will expect a <template>
tag as a direct child of the toplevel
<interface>
tag. The <template>
tag must specify the “class” attribute
which must be the type name of the widget. Optionally, the “parent”
attribute may be specified to specify the direct parent type of the widget
type; this is ignored by GtkBuilder
but can be used by UI design tools to
introspect what kind of properties and internal children exist for a given
type when the actual type does not exist.
The XML which is contained inside the <template>
tag behaves as if it were
added to the <object>
tag defining the widget itself. You may set properties
on a widget by inserting <property>
tags into the <template>
tag, and also
add <child>
tags to add children and extend a widget in the normal way you
would with <object>
tags.
Additionally, <object>
tags can also be added before and after the initial
<template>
tag in the normal way, allowing one to define auxiliary objects
which might be referenced by other widgets declared as children of the
<template>
tag.
Since, unlike the <object>
tag, the <template>
tag does not contain an
“id” attribute, if you need to refer to the instance of the object itself that
the template will create, simply refer to the template class name in an
applicable element content.
Here is an example of a template definition, which includes an example of
this in the <signal>
tag:
<interface>
<template class="FooWidget" parent="GtkBox">
<property name="orientation">horizontal</property>
<property name="spacing">4</property>
<child>
<object class="GtkButton" id="hello_button">
<property name="label">Hello World</property>
<signal name="clicked" handler="hello_button_clicked" object="FooWidget" swapped="yes"/>
</object>
</child>
<child>
<object class="GtkButton" id="goodbye_button">
<property name="label">Goodbye World</property>
</object>
</child>
</template>
</interface>
Typically, you’ll place the template fragment into a file that is
bundled with your project, using GResource
. In order to load the
template, you need to call set_template_from_resource
from the class initialization of your GtkWidget
type:
static void
foo_widget_class_init (FooWidgetClass *klass)
{
// ...
gtk_widget_class_set_template_from_resource (GTK_WIDGET_CLASS (klass),
"/com/example/ui/foowidget.ui");
}
You will also need to call init_template
from the
instance initialization function:
static void
foo_widget_init (FooWidget *self)
{
gtk_widget_init_template (GTK_WIDGET (self));
// Initialize the rest of the widget...
}
as well as calling dispose_template
from the dispose
function:
static void
foo_widget_dispose (GObject *gobject)
{
FooWidget *self = FOO_WIDGET (gobject);
// Dispose objects for which you have a reference...
// Clear the template children for this widget type
gtk_widget_dispose_template (GTK_WIDGET (self), FOO_TYPE_WIDGET);
G_OBJECT_CLASS (foo_widget_parent_class)->dispose (gobject);
}
You can access widgets defined in the template using the
get_template_child
function, but you will typically declare
a pointer in the instance private data structure of your type using the same
name as the widget in the template definition, and call
bind_template_child_full
(or one of its wrapper macros
widget_class_bind_template_child
and widget_class_bind_template_child_private
)
with that name, e.g.
typedef struct {
GtkWidget *hello_button;
GtkWidget *goodbye_button;
} FooWidgetPrivate;
G_DEFINE_TYPE_WITH_PRIVATE (FooWidget, foo_widget, GTK_TYPE_BOX)
static void
foo_widget_dispose (GObject *gobject)
{
gtk_widget_dispose_template (GTK_WIDGET (gobject), FOO_TYPE_WIDGET);
G_OBJECT_CLASS (foo_widget_parent_class)->dispose (gobject);
}
static void
foo_widget_class_init (FooWidgetClass *klass)
{
// ...
G_OBJECT_CLASS (klass)->dispose = foo_widget_dispose;
gtk_widget_class_set_template_from_resource (GTK_WIDGET_CLASS (klass),
"/com/example/ui/foowidget.ui");
gtk_widget_class_bind_template_child_private (GTK_WIDGET_CLASS (klass),
FooWidget, hello_button);
gtk_widget_class_bind_template_child_private (GTK_WIDGET_CLASS (klass),
FooWidget, goodbye_button);
}
static void
foo_widget_init (FooWidget *widget)
{
gtk_widget_init_template (GTK_WIDGET (widget));
}
You can also use bind_template_callback_full
(or
is wrapper macro widget_class_bind_template_callback
) to connect
a signal callback defined in the template with a function visible in the
scope of the class, e.g.
// the signal handler has the instance and user data swapped
// because of the swapped="yes" attribute in the template XML
static void
hello_button_clicked (FooWidget *self,
GtkButton *button)
{
g_print ("Hello, world!\n");
}
static void
foo_widget_class_init (FooWidgetClass *klass)
{
// ...
gtk_widget_class_set_template_from_resource (GTK_WIDGET_CLASS (klass),
"/com/example/ui/foowidget.ui");
gtk_widget_class_bind_template_callback (GTK_WIDGET_CLASS (klass), hello_button_clicked);
}
Methods#
- class Widget
- action_set_enabled(action_name: str, enabled: bool) None #
Enable or disable an action installed with
install_action()
.- Parameters:
action_name – action name, such as “clipboard.paste”
enabled – whether the action is now enabled
- activate() bool #
For widgets that can be “activated” (buttons, menu items, etc.), this function activates them.
The activation will emit the signal set using
set_activate_signal
during class initialization.Activation is what happens when you press Enter on a widget during key navigation.
If you wish to handle the activation keybinding yourself, it is recommended to use
add_shortcut
with an action created withnew
.If
widget
isn’t activatable, the function returnsFalse
.
- activate_action(name: str, args: Variant | None = None) bool #
Looks up the action in the action groups associated with
widget
and its ancestors, and activates it.This is a wrapper around
activate_action_variant
that constructs theargs
variant according toformat_string
.- Parameters:
name – the name of the action to activate
args
- add_controller(controller: EventController) None #
Adds
controller
towidget
so that it will receive events.You will usually want to call this function right after creating any kind of
EventController
.- Parameters:
controller – a
GtkEventController
that hasn’t been added to a widget yet
- add_css_class(css_class: str) None #
Adds a style class to
widget
.After calling this function, the widget’s style will match for
css_class
, according to CSS matching rules.Use
remove_css_class
to remove the style again.- Parameters:
css_class – The style class to add to
widget
, without the leading ‘.’ used for notation of style classes
- add_mnemonic_label(label: Widget) None #
Adds a widget to the list of mnemonic labels for this widget.
See
list_mnemonic_labels
. Note the list of mnemonic labels for the widget is cleared when the widget is destroyed, so the caller must make sure to update its internal state at this point as well.- Parameters:
label – a
GtkWidget
that acts as a mnemonic label forwidget
- add_tick_callback(callback: Callable[[Widget, FrameClock, Any], bool], user_data: Any = None) int #
Queues an animation frame update and adds a callback to be called before each frame.
Until the tick callback is removed, it will be called frequently (usually at the frame rate of the output device or as quickly as the application can be repainted, whichever is slower). For this reason, is most suitable for handling graphics that change every frame or every few frames. The tick callback does not automatically imply a relayout or repaint. If you want a repaint or relayout, and aren’t changing widget properties that would trigger that (for example, changing the text of a
GtkLabel
), then you will have to callqueue_resize
orqueue_draw
yourself.get_frame_time
should generally be used for timing continuous animations andget_predicted_presentation_time
if you are trying to display isolated frames at particular times.This is a more convenient alternative to connecting directly to the
update
signal ofGdkFrameClock
, since you don’t have to worry about when aGdkFrameClock
is assigned to a widget.- Parameters:
callback – function to call for updating animations
user_data – data to pass to
callback
- allocate(width: int, height: int, baseline: int, transform: Transform | None = None) None #
This function is only used by
GtkWidget
subclasses, to assign a size, position and (optionally) baseline to their child widgets.In this function, the allocation and baseline may be adjusted. The given allocation will be forced to be bigger than the widget’s minimum size, as well as at least 0×0 in size.
For a version that does not take a transform, see
size_allocate
.- Parameters:
width – New width of
widget
height – New height of
widget
baseline – New baseline of
widget
, or -1transform – Transformation to be applied to
widget
- classmethod bind_template_callback_full(callback_name: str, callback_symbol: Callable[[], None]) None #
- Parameters:
callback_name
callback_symbol
- classmethod bind_template_child_full(name: str, internal_child: bool, struct_offset: int) None #
- Parameters:
name
internal_child
struct_offset
- child_focus(direction: DirectionType) bool #
Called by widgets as the user moves around the window using keyboard shortcuts.
The
direction
argument indicates what kind of motion is taking place (up, down, left, right, tab forward, tab backward).This function calls the
focus
virtual function; widgets can override the virtual function in order to implement appropriate focus behavior.The default
focus()
virtual function for a widget should returnTRUE
if moving indirection
left the focus on a focusable location inside that widget, andFALSE
if moving indirection
moved the focus outside the widget. When returningTRUE
, widgets normally callgrab_focus
to place the focus accordingly; when returningFALSE
, they don’t modify the current focus location.This function is used by custom widget implementations; if you’re writing an app, you’d use
grab_focus
to move the focus to a particular widget.- Parameters:
direction – direction of focus movement
- compute_bounds(target: Widget) Tuple[bool, Rect] #
Computes the bounds for
widget
in the coordinate space oftarget
.The bounds of widget are (the bounding box of) the region that it is expected to draw in. See the coordinate system overview to learn more.
If the operation is successful,
True
is returned. Ifwidget
has no bounds or the bounds cannot be expressed intarget
's coordinate space (for example if both widgets are in different windows),False
is returned andbounds
is set to the zero rectangle.It is valid for
widget
andtarget
to be the same widget.- Parameters:
target – the
GtkWidget
- compute_expand(orientation: Orientation) bool #
Computes whether a container should give this widget extra space when possible.
Containers should check this, rather than looking at
get_hexpand
orget_vexpand
.This function already checks whether the widget is visible, so visibility does not need to be checked separately. Non-visible widgets are not expanded.
The computed expand value uses either the expand setting explicitly set on the widget itself, or, if none has been explicitly set, the widget may expand if some of its children do.
- Parameters:
orientation – expand direction
- compute_point(target: Widget, point: Point) Tuple[bool, Point] #
Translates the given
point
inwidget
's coordinates to coordinates relative totarget
’s coordinate system.In order to perform this operation, both widgets must share a common ancestor.
- Parameters:
target – the
GtkWidget
to transform intopoint – a point in
widget
's coordinate system
- compute_transform(target: Widget) Tuple[bool, Matrix] #
Computes a matrix suitable to describe a transformation from
widget
's coordinate system intotarget
's coordinate system.The transform can not be computed in certain cases, for example when
widget
andtarget
do not share a common ancestor. In that caseout_transform
gets set to the identity matrix.To learn more about widget coordinate systems, see the coordinate system overview.
- Parameters:
target – the target widget that the matrix will transform to
- contains(x: float, y: float) bool #
Tests if the point at (
x
,y
) is contained inwidget
.The coordinates for (
x
,y
) must be in widget coordinates, so (0, 0) is assumed to be the top left ofwidget
's content area.- Parameters:
x – X coordinate to test, relative to
widget
's originy – Y coordinate to test, relative to
widget
's origin
- create_pango_context() Context #
Creates a new
PangoContext
with the appropriate font map, font options, font description, and base direction for drawing text for this widget.See also
get_pango_context
.
- create_pango_layout(text: str | None = None) Layout #
Creates a new
PangoLayout
with the appropriate font map, font description, and base direction for drawing text for this widget.If you keep a
PangoLayout
created in this way around, you need to re-create it when the widgetPangoContext
is replaced. This can be tracked by listening to changes of theroot
property on the widget.- Parameters:
text – text to set on the layout
- dispose_template(widget_type: GType) None #
Clears the template children for the given widget.
This function is the opposite of
init_template
, and it is used to clear all the template children from a widget instance. If you bound a template child to a field in the instance structure, or in the instance private data structure, the field will be set toNULL
after this function returns.You should call this function inside the
GObjectClass.dispose()
implementation of any widget that calledgtk_widget_init_template()
. Typically, you will want to call this function last, right before chaining up to the parent type’s dispose implementation, e.g.static void some_widget_dispose (GObject *gobject) { SomeWidget *self = SOME_WIDGET (gobject); // Clear the template data for SomeWidget gtk_widget_dispose_template (GTK_WIDGET (self), SOME_TYPE_WIDGET); G_OBJECT_CLASS (some_widget_parent_class)->dispose (gobject); }
Added in version 4.8.
- Parameters:
widget_type – the type of the widget to finalize the template for
- do_css_changed(self, change: CssStyleChange) None #
- Parameters:
change
- do_direction_changed(self, previous_direction: TextDirection) None #
- Parameters:
previous_direction
- do_focus(self, direction: DirectionType) bool #
- Parameters:
direction
- do_get_request_mode(self) SizeRequestMode #
- Parameters:
direction
- do_measure(self, orientation: Orientation, for_size: int) Tuple[int, int, int, int] #
- Parameters:
orientation
for_size
- do_move_focus(self, direction: DirectionType) None #
- Parameters:
direction
- do_query_tooltip(self, x: int, y: int, keyboard_tooltip: bool, tooltip: Tooltip) bool #
- Parameters:
x
y
keyboard_tooltip
tooltip
- do_size_allocate(self, width: int, height: int, baseline: int) None #
- Parameters:
width
height
baseline
- do_state_flags_changed(self, previous_state_flags: StateFlags) None #
- Parameters:
previous_state_flags
- do_system_setting_changed(self, settings: SystemSetting) None #
- Parameters:
settings
- drag_check_threshold(start_x: int, start_y: int, current_x: int, current_y: int) bool #
Checks to see if a drag movement has passed the GTK drag threshold.
- Parameters:
start_x – X coordinate of start of drag
start_y – Y coordinate of start of drag
current_x – current X coordinate
current_y – current Y coordinate
- error_bell() None #
Notifies the user about an input-related error on this widget.
If the
gtk_error_bell
setting isTrue
, it callsbeep
, otherwise it does nothing.Note that the effect of
beep
can be configured in many ways, depending on the windowing backend and the desktop environment or window manager that is used.
- get_allocated_baseline() int #
Returns the baseline that has currently been allocated to
widget
.This function is intended to be used when implementing handlers for the
GtkWidget
Class.snapshot() function, and when allocating child widgets inGtkWidget
Class.size_allocate().Deprecated since version 4.12: Use
get_baseline
instead
- get_allocated_height() int #
Returns the height that has currently been allocated to
widget
.To learn more about widget sizes, see the coordinate system overview.
Deprecated since version 4.12: Use
get_height
instead
- get_allocated_width() int #
Returns the width that has currently been allocated to
widget
.To learn more about widget sizes, see the coordinate system overview.
Deprecated since version 4.12: Use
get_width
instead
- get_allocation() Rectangle #
Retrieves the widget’s allocation.
Note, when implementing a layout container: a widget’s allocation will be its “adjusted” allocation, that is, the widget’s parent typically calls
size_allocate
with an allocation, and that allocation is then adjusted (to handle margin and alignment for example) before assignment to the widget.get_allocation
returns the adjusted allocation that was actually assigned to the widget. The adjusted allocation is guaranteed to be completely contained within thesize_allocate
allocation, however.So a layout container is guaranteed that its children stay inside the assigned bounds, but not that they have exactly the bounds the container assigned.
Deprecated since version 4.12: Use
compute_bounds
,get_width
orget_height
instead.
- get_ancestor(widget_type: GType) Widget | None #
Gets the first ancestor of
widget
with typewidget_type
.For example,
gtk_widget_get_ancestor (widget, GTK_TYPE_BOX)
gets the firstGtkBox
that’s an ancestor ofwidget
. No reference will be added to the returned widget; it should not be unreferenced.Note that unlike
is_ancestor
, this function considerswidget
to be an ancestor of itself.- Parameters:
widget_type – ancestor type
- get_baseline() int #
Returns the baseline that has currently been allocated to
widget
.This function is intended to be used when implementing handlers for the
GtkWidget
Class.snapshot() function, and when allocating child widgets inGtkWidget
Class.size_allocate().Added in version 4.12.
- get_can_focus() bool #
Determines whether the input focus can enter
widget
or any of its children.See
set_focusable
.
- get_child_visible() bool #
Gets the value set with
set_child_visible()
.If you feel a need to use this function, your code probably needs reorganization.
This function is only useful for container implementations and should never be called by an application.
- get_clipboard() Clipboard #
Gets the clipboard object for
widget
.This is a utility function to get the clipboard object for the
GdkDisplay
thatwidget
is using.Note that this function always works, even when
widget
is not realized yet.
- get_color() RGBA #
Gets the current foreground color for the widget’s CSS style.
This function should only be used in snapshot implementations that need to do custom drawing with the foreground color.
Added in version 4.10.
- get_cursor() Cursor | None #
Queries the cursor set on
widget
.See
set_cursor
for details.
- classmethod get_default_direction() TextDirection #
Obtains the current default reading direction.
- get_direction() TextDirection #
Gets the reading direction for a particular widget.
See
set_direction
.
- get_display() Display #
Get the
GdkDisplay
for the toplevel window associated with this widget.This function can only be called after the widget has been added to a widget hierarchy with a
GtkWindow
at the top.In general, you should only create display specific resources when a widget has been realized, and you should free those resources when the widget is unrealized.
- get_first_child() Widget | None #
Returns the widget’s first child.
This API is primarily meant for widget implementations.
- get_focus_on_click() bool #
Returns whether the widget should grab focus when it is clicked with the mouse.
See
set_focus_on_click
.
- get_focusable() bool #
Determines whether
widget
can own the input focus.See
set_focusable
.
- get_font_map() FontMap | None #
Gets the font map of
widget
.See
set_font_map
.
- get_font_options() FontOptions | None #
Returns the
cairo_font_options_t
of widget.Seee
set_font_options
.Deprecated since version 4.16: Please do not use it in newly written code
- get_frame_clock() FrameClock | None #
Obtains the frame clock for a widget.
The frame clock is a global “ticker” that can be used to drive animations and repaints. The most common reason to get the frame clock is to call
get_frame_time
, in order to get a time to use for animating. For example you might record the start of the animation with an initial value fromget_frame_time
, and then update the animation by callingget_frame_time
again during each repaint.request_phase
will result in a new frame on the clock, but won’t necessarily repaint any widgets. To repaint a widget, you have to usequeue_draw
which invalidates the widget (thus scheduling it to receive a draw on the next frame).queue_draw()
will also end up requesting a frame on the appropriate frame clock.A widget’s frame clock will not change while the widget is mapped. Reparenting a widget (which implies a temporary unmap) can change the widget’s frame clock.
Unrealized widgets do not have a frame clock.
- get_halign() Align #
Gets the horizontal alignment of
widget
.For backwards compatibility reasons this method will never return one of the baseline alignments, but instead it will convert it to
GTK_ALIGN_FILL
orGTK_ALIGN_CENTER
.Baselines are not supported for horizontal alignment.
- get_height() int #
Returns the content height of the widget.
This function returns the height passed to its size-allocate implementation, which is the height you should be using in
snapshot
.For pointer events, see
contains
.To learn more about widget sizes, see the coordinate system overview.
- get_hexpand() bool #
Gets whether the widget would like any available extra horizontal space.
When a user resizes a
GtkWindow
, widgets with expand=TRUE generally receive the extra space. For example, a list or scrollable area or document in your window would often be set to expand.Containers should use
compute_expand
rather than this function, to see whether a widget, or any of its children, has the expand flag set. If any child of a widget wants to expand, the parent may ask to expand also.This function only looks at the widget’s own hexpand flag, rather than computing whether the entire widget tree rooted at this widget wants to expand.
- get_hexpand_set() bool #
Gets whether
set_hexpand()
has been used to explicitly set the expand flag on this widget.If
hexpand
property is set, then it overrides any computed expand value based on child widgets. Ifhexpand
is not set, then the expand value depends on whether any children of the widget would like to expand.There are few reasons to use this function, but it’s here for completeness and consistency.
- get_last_child() Widget | None #
Returns the widget’s last child.
This API is primarily meant for widget implementations.
- get_layout_manager() LayoutManager | None #
Retrieves the layout manager used by
widget
.See
set_layout_manager
.
- classmethod get_layout_manager_type() GType #
- get_native() Native | None #
Returns the nearest
GtkNative
ancestor ofwidget
.This function will return
None
if the widget is not contained inside a widget tree with a native ancestor.GtkNative
widgets will return themselves here.
- get_next_sibling() Widget | None #
Returns the widget’s next sibling.
This API is primarily meant for widget implementations.
- get_opacity() float #
Fetches
the requested opacity for this widget.See
set_opacity
.
- get_pango_context() Context #
Gets a
PangoContext
with the appropriate font map, font description, and base direction for this widget.Unlike the context returned by
create_pango_context
, this context is owned by the widget (it can be used until the screen for the widget changes or the widget is removed from its toplevel), and will be updated to match any changes to the widget’s attributes. This can be tracked by listening to changes of theroot
property on the widget.
- get_preferred_size() Tuple[Requisition, Requisition] #
Retrieves the minimum and natural size of a widget, taking into account the widget’s preference for height-for-width management.
This is used to retrieve a suitable size by container widgets which do not impose any restrictions on the child placement. It can be used to deduce toplevel window and menu sizes as well as child widgets in free-form containers such as
GtkFixed
.Handle with care. Note that the natural height of a height-for-width widget will generally be a smaller size than the minimum height, since the required height for the natural width is generally smaller than the required height for the minimum width.
Use
measure
if you want to support baseline alignment.
- get_prev_sibling() Widget | None #
Returns the widget’s previous sibling.
This API is primarily meant for widget implementations.
- get_primary_clipboard() Clipboard #
Gets the primary clipboard of
widget
.This is a utility function to get the primary clipboard object for the
GdkDisplay
thatwidget
is using.Note that this function always works, even when
widget
is not realized yet.
- get_receives_default() bool #
Determines whether
widget
is always treated as the default widget within its toplevel when it has the focus, even if another widget is the default.See
set_receives_default
.
- get_request_mode() SizeRequestMode #
Gets whether the widget prefers a height-for-width layout or a width-for-height layout.
Single-child widgets generally propagate the preference of their child, more complex widgets need to request something either in context of their children or in context of their allocation capabilities.
- get_root() Root | None #
Returns the
GtkRoot
widget ofwidget
.This function will return
None
if the widget is not contained inside a widget tree with a root widget.GtkRoot
widgets will return themselves here.
- get_scale_factor() int #
Retrieves the internal scale factor that maps from window coordinates to the actual device pixels.
On traditional systems this is 1, on high density outputs, it can be a higher value (typically 2).
See
get_scale_factor
.
- get_sensitive() bool #
Returns the widget’s sensitivity.
This function returns the value that has been set using
set_sensitive
).The effective sensitivity of a widget is however determined by both its own and its parent widget’s sensitivity. See
is_sensitive
.
- get_settings() Settings #
Gets the settings object holding the settings used for this widget.
Note that this function can only be called when the
GtkWidget
is attached to a toplevel, since the settings object is specific to a particularGdkDisplay
. If you want to monitor the widget for changes in its settings, connect to thenotify::display
signal.
- get_size(orientation: Orientation) int #
Returns the content width or height of the widget.
Which dimension is returned depends on
orientation
.This is equivalent to calling
get_width
forHORIZONTAL
orget_height
forVERTICAL
, but can be used when writing orientation-independent code, such as when implementingOrientable
widgets.To learn more about widget sizes, see the coordinate system overview.
- Parameters:
orientation – the orientation to query
- get_size_request() Tuple[int, int] #
Gets the size request that was explicitly set for the widget using
set_size_request()
.A value of -1 stored in
width
orheight
indicates that that dimension has not been set explicitly and the natural requisition of the widget will be used instead. Seeset_size_request
. To get the size a widget will actually request, callmeasure
instead of this function.
- get_state_flags() StateFlags #
Returns the widget state as a flag set.
It is worth mentioning that the effective
INSENSITIVE
state will be returned, that is, also based on parent insensitivity, even ifwidget
itself is sensitive.Also note that if you are looking for a way to obtain the
StateFlags
to pass to aStyleContext
method, you should look atget_state
.
- get_style_context() StyleContext #
Returns the style context associated to
widget
.The returned object is guaranteed to be the same for the lifetime of
widget
.Deprecated since version 4.10: Style contexts will be removed in GTK 5
- get_template_child(widget_type: GType, name: str) Object #
Fetch an object build from the template XML for
widget_type
in thiswidget
instance.This will only report children which were previously declared with
bind_template_child_full
or one of its variants.This function is only meant to be called for code which is private to the
widget_type
which declared the child and is meant for language bindings which cannot easily make use of the GObject structure offsets.- Parameters:
widget_type – The
GType
to get a template child forname – The “id” of the child defined in the template XML
- get_tooltip_markup() str | None #
Gets the contents of the tooltip for
widget
.If the tooltip has not been set using
set_tooltip_markup
, this function returnsNone
.
- get_tooltip_text() str | None #
Gets the contents of the tooltip for
widget
.If the
widget
's tooltip was set usingset_tooltip_markup
, this function will return the escaped text.
- get_vexpand() bool #
Gets whether the widget would like any available extra vertical space.
See
get_hexpand
for more detail.
- get_vexpand_set() bool #
Gets whether
set_vexpand()
has been used to explicitly set the expand flag on this widget.See
get_hexpand_set
for more detail.
- get_visible() bool #
Determines whether the widget is visible.
If you want to take into account whether the widget’s parent is also marked as visible, use
is_visible
instead.This function does not check if the widget is obscured in any way.
See
set_visible
.
- get_width() int #
Returns the content width of the widget.
This function returns the width passed to its size-allocate implementation, which is the width you should be using in
snapshot
.For pointer events, see
contains
.To learn more about widget sizes, see the coordinate system overview.
- grab_focus() bool #
Causes
widget
to have the keyboard focus for theGtkWindow
it’s inside.If
widget
is not focusable, or itsgrab_focus
implementation cannot transfer the focus to a descendant ofwidget
that is focusable, it will not take focus andFalse
will be returned.Calling
grab_focus
on an already focused widget is allowed, should not have an effect, and returnTrue
.
- has_css_class(css_class: str) bool #
Returns whether
css_class
is currently applied towidget
.- Parameters:
css_class – A style class, without the leading ‘.’ used for notation of style classes
- has_focus() bool #
Determines if the widget has the global input focus.
See
is_focus
for the difference between having the global input focus, and only having the focus within a toplevel.
- has_visible_focus() bool #
Determines if the widget should show a visible indication that it has the global input focus.
This is a convenience function that takes into account whether focus indication should currently be shown in the toplevel window of
widget
. Seeget_focus_visible
for more information about focus indication.To find out if the widget has the global input focus, use
has_focus
.
- hide() None #
Reverses the effects of
show()
.This is causing the widget to be hidden (invisible to the user).
Deprecated since version 4.10: Use
set_visible
instead
- in_destruction() bool #
Returns whether the widget is currently being destroyed.
This information can sometimes be used to avoid doing unnecessary work.
- init_template() None #
Creates and initializes child widgets defined in templates.
This function must be called in the instance initializer for any class which assigned itself a template using
set_template
.It is important to call this function in the instance initializer of a
GtkWidget
subclass and not inGObject.constructed()
orGObject.constructor()
for two reasons:- derived widgets will assume that the composite widgets
defined by its parent classes have been created in their relative instance initializers
- when calling
g_object_new()
on a widget with composite templates, it’s important to build the composite widgets before the construct properties are set. Properties passed to
g_object_new()
should take precedence over properties set in the private template XML
- when calling
A good rule of thumb is to call this function as the first thing in an instance initialization function.
- insert_action_group(name: str, group: ActionGroup | None = None) None #
Inserts
group
intowidget
.Children of
widget
that implementActionable
can then be associated with actions ingroup
by setting their “action-name” toprefix
.``action-name``.Note that inheritance is defined for individual actions. I.e. even if you insert a group with prefix
prefix
, actions with the same prefix will still be inherited from the parent, unless the group contains an action with the same name.If
group
isNone
, a previously inserted group forname
is removed fromwidget
.- Parameters:
name – the prefix for actions in
group
group – a
GActionGroup
, orNone
to remove the previously inserted group forname
- insert_after(parent: Widget, previous_sibling: Widget | None = None) None #
Inserts
widget
into the child widget list ofparent
.It will be placed after
previous_sibling
, or at the beginning ifprevious_sibling
isNone
.After calling this function,
gtk_widget_get_prev_sibling(widget)
will returnprevious_sibling
.If
parent
is already set as the parent widget ofwidget
, this function can also be used to reorderwidget
in the child widget list ofparent
.This API is primarily meant for widget implementations; if you are just using a widget, you must use its own API for adding children.
- Parameters:
parent – the parent
GtkWidget
to insertwidget
intoprevious_sibling – the new previous sibling of
widget
- insert_before(parent: Widget, next_sibling: Widget | None = None) None #
Inserts
widget
into the child widget list ofparent
.It will be placed before
next_sibling
, or at the end ifnext_sibling
isNone
.After calling this function,
gtk_widget_get_next_sibling(widget)
will returnnext_sibling
.If
parent
is already set as the parent widget ofwidget
, this function can also be used to reorderwidget
in the child widget list ofparent
.This API is primarily meant for widget implementations; if you are just using a widget, you must use its own API for adding children.
- Parameters:
parent – the parent
GtkWidget
to insertwidget
intonext_sibling – the new next sibling of
widget
- classmethod install_action(action_name: str, parameter_type: str | None, activate: Callable[[Widget, str, Variant | None], None]) None #
- Parameters:
action_name
parameter_type
activate
- classmethod install_property_action(action_name: str, property_name: str) None #
- Parameters:
action_name
property_name
- is_ancestor(ancestor: Widget) bool #
Determines whether
widget
is somewhere insideancestor
, possibly with intermediate containers.- Parameters:
ancestor – another
GtkWidget
- is_drawable() bool #
Determines whether
widget
can be drawn to.A widget can be drawn if it is mapped and visible.
- is_focus() bool #
Determines if the widget is the focus widget within its toplevel.
This does not mean that the
has_focus
property is necessarily set;has_focus
will only be set if the toplevel widget additionally has the global input focus.
- is_sensitive() bool #
Returns the widget’s effective sensitivity.
This means it is sensitive itself and also its parent widget is sensitive.
- is_visible() bool #
Determines whether the widget and all its parents are marked as visible.
This function does not check if the widget is obscured in any way.
See also
get_visible
andset_visible
.
Emits the
::keynav-failed
signal on the widget.This function should be called whenever keyboard navigation within a single widget hits a boundary.
The return value of this function should be interpreted in a way similar to the return value of
child_focus
. WhenTrue
is returned, stay in the widget, the failed keyboard navigation is OK and/or there is nowhere we can/should move the focus to. WhenFalse
is returned, the caller should continue with keyboard navigation outside the widget, e.g. by callingchild_focus
on the widget’s toplevel.The default
keynav_failed
handler returnsFalse
forTAB_FORWARD
andTAB_BACKWARD
. For the other values ofGtkDirectionType
it returnsTrue
.Whenever the default handler returns
True
, it also callserror_bell
to notify the user of the failed keyboard navigation.A use case for providing an own implementation of ::keynav-failed (either by connecting to it or by overriding it) would be a row of
Entry
widgets where the user should be able to navigate the entire row with the cursor keys, as e.g. known from user interfaces that require entering license keys.- Parameters:
direction – direction of focus movement
- list_mnemonic_labels() list[Widget] #
Returns the widgets for which this widget is the target of a mnemonic.
Typically, these widgets will be labels. See, for example,
set_mnemonic_widget
.The widgets in the list are not individually referenced. If you want to iterate through the list and perform actions involving callbacks that might destroy the widgets, you must call
g_list_foreach (result, (GFunc)g_object_ref, NULL)
first, and then unref all the widgets afterwards.
- map() None #
Causes a widget to be mapped if it isn’t already.
This function is only for use in widget implementations.
- measure(orientation: Orientation, for_size: int) Tuple[int, int, int, int] #
Measures
widget
in the orientationorientation
and for the givenfor_size
.As an example, if
orientation
isHORIZONTAL
andfor_size
is 300, this functions will compute the minimum and natural width ofwidget
if it is allocated at a height of 300 pixels.See GtkWidget’s geometry management section for a more details on implementing
GtkWidgetClass.measure()
.- Parameters:
orientation – the orientation to measure
for_size – Size for the opposite of
orientation
, i.e. iforientation
isHORIZONTAL
, this is the height the widget should be measured with. TheVERTICAL
case is analogous. This way, both height-for-width and width-for-height requests can be implemented. If no size is known, -1 can be passed.
- mnemonic_activate(group_cycling: bool) bool #
Emits the ::mnemonic-activate signal.
See
mnemonic_activate
.- Parameters:
group_cycling –
True
if there are other widgets with the same mnemonic
- observe_children() ListModel #
Returns a
GListModel
to track the children ofwidget
.Calling this function will enable extra internal bookkeeping to track children and emit signals on the returned listmodel. It may slow down operations a lot.
Applications should try hard to avoid calling this function because of the slowdowns.
- observe_controllers() ListModel #
Returns a
GListModel
to track theEventController
s ofwidget
.Calling this function will enable extra internal bookkeeping to track controllers and emit signals on the returned listmodel. It may slow down operations a lot.
Applications should try hard to avoid calling this function because of the slowdowns.
- pick(x: float, y: float, flags: PickFlags) Widget | None #
Finds the descendant of
widget
closest to the point (x
,y
).The point must be given in widget coordinates, so (0, 0) is assumed to be the top left of
widget
's content area.Usually widgets will return
None
if the given coordinate is not contained inwidget
checked viacontains
. Otherwise they will recursively try to find a child that does not returnNone
. Widgets are however free to customize their picking algorithm.This function is used on the toplevel to determine the widget below the mouse cursor for purposes of hover highlighting and delivering events.
- Parameters:
x – X coordinate to test, relative to
widget
's originy – Y coordinate to test, relative to
widget
's originflags – Flags to influence what is picked
- classmethod query_action(index_: int) Tuple[bool, GType, str, VariantType | None, str | None] #
- Parameters:
index
- queue_allocate() None #
Flags the widget for a rerun of the
size_allocate
function.Use this function instead of
queue_resize
when thewidget
's size request didn’t change but it wants to reposition its contents.An example user of this function is
set_halign
.This function is only for use in widget implementations.
- queue_draw() None #
Schedules this widget to be redrawn in the paint phase of the current or the next frame.
This means
widget
'ssnapshot
implementation will be called.
- queue_resize() None #
Flags a widget to have its size renegotiated.
This should be called when a widget for some reason has a new size request. For example, when you change the text in a
Label
, the label queues a resize to ensure there’s enough space for the new text.Note that you cannot call
queue_resize()
on a widget from inside its implementation of thesize_allocate
virtual method. Calls toqueue_resize()
from insidesize_allocate
will be silently ignored.This function is only for use in widget implementations.
- realize() None #
Creates the GDK resources associated with a widget.
Normally realization happens implicitly; if you show a widget and all its parent containers, then the widget will be realized and mapped automatically.
Realizing a widget requires all the widget’s parent widgets to be realized; calling this function realizes the widget’s parents in addition to
widget
itself. If a widget is not yet inside a toplevel window when you realize it, bad things will happen.This function is primarily used in widget implementations, and isn’t very useful otherwise. Many times when you think you might need it, a better approach is to connect to a signal that will be called after the widget is realized automatically, such as
realize
.
- remove_controller(controller: EventController) None #
Removes
controller
fromwidget
, so that it doesn’t process events anymore.It should not be used again.
Widgets will remove all event controllers automatically when they are destroyed, there is normally no need to call this function.
- Parameters:
controller – a
GtkEventController
- remove_css_class(css_class: str) None #
Removes a style from
widget
.After this, the style of
widget
will stop matching forcss_class
.- Parameters:
css_class – The style class to remove from
widget
, without the leading ‘.’ used for notation of style classes
- remove_mnemonic_label(label: Widget) None #
Removes a widget from the list of mnemonic labels for this widget.
See
list_mnemonic_labels
. The widget must have previously been added to the list withadd_mnemonic_label
.- Parameters:
label – a
GtkWidget
that was previously set as a mnemonic label forwidget
withadd_mnemonic_label
- remove_tick_callback(id: int) None #
Removes a tick callback previously registered with
add_tick_callback()
.- Parameters:
id – an id returned by
add_tick_callback
- classmethod set_accessible_role(accessible_role: AccessibleRole) None #
- Parameters:
accessible_role
- set_can_focus(can_focus: bool) None #
Specifies whether the input focus can enter the widget or any of its children.
Applications should set
can_focus
toFalse
to mark a widget as for pointer/touch use only.Note that having
can_focus
beTrue
is only one of the necessary conditions for being focusable. A widget must also be sensitive and focusable and not have an ancestor that is marked as not can-focus in order to receive input focus.See
grab_focus
for actually setting the input focus on a widget.- Parameters:
can_focus – whether or not the input focus can enter the widget or any of its children
- set_can_target(can_target: bool) None #
Sets whether
widget
can be the target of pointer events.- Parameters:
can_target – whether this widget should be able to receive pointer events
- set_child_visible(child_visible: bool) None #
Sets whether
widget
should be mapped along with its parent.The child visibility can be set for widget before it is added to a container with
set_parent
, to avoid mapping children unnecessary before immediately unmapping them. However it will be reset to its default state ofTrue
when the widget is removed from a container.Note that changing the child visibility of a widget does not queue a resize on the widget. Most of the time, the size of a widget is computed from all visible children, whether or not they are mapped. If this is not the case, the container can queue a resize itself.
This function is only useful for container implementations and should never be called by an application.
- Parameters:
child_visible – if
True
,widget
should be mapped along with its parent.
- set_css_classes(classes: list[str]) None #
Clear all style classes applied to
widget
and replace them withclasses
.- Parameters:
classes –
None
-terminated list of style classes to apply towidget
.
- set_cursor(cursor: Cursor | None = None) None #
Sets the cursor to be shown when pointer devices point towards
widget
.If the
cursor
is NULL,widget
will use the cursor inherited from the parent widget.- Parameters:
cursor – the new cursor
- set_cursor_from_name(name: str | None = None) None #
Sets a named cursor to be shown when pointer devices point towards
widget
.This is a utility function that creates a cursor via
new_from_name
and then sets it onwidget
withset_cursor
. See those functions for details.On top of that, this function allows
name
to beNone
, which will do the same as callingset_cursor
with aNone
cursor.- Parameters:
name – The name of the cursor
- classmethod set_default_direction() None #
Sets the default reading direction for widgets.
See
set_direction
.
- set_direction(dir: TextDirection) None #
Sets the reading direction on a particular widget.
This direction controls the primary direction for widgets containing text, and also the direction in which the children of a container are packed. The ability to set the direction is present in order so that correct localization into languages with right-to-left reading directions can be done. Generally, applications will let the default reading direction present, except for containers where the containers are arranged in an order that is explicitly visual rather than logical (such as buttons for text justification).
If the direction is set to
NONE
, then the value set byset_default_direction
will be used.- Parameters:
dir – the new direction
- set_focus_child(child: Widget | None = None) None #
Set
child
as the current focus child ofwidget
.This function is only suitable for widget implementations. If you want a certain widget to get the input focus, call
grab_focus
on it.- Parameters:
child – a direct child widget of
widget
orNone
to unset the focus child ofwidget
- set_focus_on_click(focus_on_click: bool) None #
Sets whether the widget should grab focus when it is clicked with the mouse.
Making mouse clicks not grab focus is useful in places like toolbars where you don’t want the keyboard focus removed from the main area of the application.
- Parameters:
focus_on_click – whether the widget should grab focus when clicked with the mouse
- set_focusable(focusable: bool) None #
Specifies whether
widget
can own the input focus.Widget implementations should set
focusable
toTrue
in their init() function if they want to receive keyboard input.Note that having
focusable
beTrue
is only one of the necessary conditions for being focusable. A widget must also be sensitive and can-focus and not have an ancestor that is marked as not can-focus in order to receive input focus.See
grab_focus
for actually setting the input focus on a widget.- Parameters:
focusable – whether or not
widget
can own the input focus
- set_font_map(font_map: FontMap | None = None) None #
Sets the font map to use for Pango rendering.
The font map is the object that is used to look up fonts. Setting a custom font map can be useful in special situations, e.g. when you need to add application-specific fonts to the set of available fonts.
When not set, the widget will inherit the font map from its parent.
- Parameters:
font_map – a
PangoFontMap
, orNone
to unset any previously set font map
- set_font_options(options: FontOptions | None = None) None #
Sets the
cairo_font_options_t
used for Pango rendering in this widget.When not set, the default font options for the
GdkDisplay
will be used.Deprecated since version 4.16: Please do not use it in newly written code
- Parameters:
options – a
cairo_font_options_t
to unset any previously set default font options
- set_halign(align: Align) None #
Sets the horizontal alignment of
widget
.- Parameters:
align – the horizontal alignment
- set_has_tooltip(has_tooltip: bool) None #
Sets the
has-tooltip
property onwidget
tohas_tooltip
.- Parameters:
has_tooltip – whether or not
widget
has a tooltip.
- set_hexpand(expand: bool) None #
Sets whether the widget would like any available extra horizontal space.
When a user resizes a
GtkWindow
, widgets with expand=TRUE generally receive the extra space. For example, a list or scrollable area or document in your window would often be set to expand.Call this function to set the expand flag if you would like your widget to become larger horizontally when the window has extra room.
By default, widgets automatically expand if any of their children want to expand. (To see if a widget will automatically expand given its current children and state, call
compute_expand
. A container can decide how the expandability of children affects the expansion of the container by overriding the compute_expand virtual method onGtkWidget
.).Setting hexpand explicitly with this function will override the automatic expand behavior.
This function forces the widget to expand or not to expand, regardless of children. The override occurs because
set_hexpand
sets the hexpand-set property (seeset_hexpand_set
) which causes the widget’s hexpand value to be used, rather than looking at children and widget state.- Parameters:
expand – whether to expand
- set_hexpand_set(set: bool) None #
Sets whether the hexpand flag will be used.
The
hexpand_set
property will be set automatically when you callset_hexpand
to set hexpand, so the most likely reason to use this function would be to unset an explicit expand flag.If hexpand is set, then it overrides any computed expand value based on child widgets. If hexpand is not set, then the expand value depends on whether any children of the widget would like to expand.
There are few reasons to use this function, but it’s here for completeness and consistency.
- Parameters:
set – value for hexpand-set property
- set_layout_manager(layout_manager: LayoutManager | None = None) None #
Sets the layout manager delegate instance that provides an implementation for measuring and allocating the children of
widget
.- Parameters:
layout_manager – a
GtkLayoutManager
- set_margin_bottom(margin: int) None #
Sets the bottom margin of
widget
.- Parameters:
margin – the bottom margin
- set_margin_end(margin: int) None #
Sets the end margin of
widget
.- Parameters:
margin – the end margin
- set_margin_start(margin: int) None #
Sets the start margin of
widget
.- Parameters:
margin – the start margin
- set_margin_top(margin: int) None #
Sets the top margin of
widget
.- Parameters:
margin – the top margin
- set_name(name: str) None #
Sets a widgets name.
Setting a name allows you to refer to the widget from a CSS file. You can apply a style to widgets with a particular name in the CSS file. See the documentation for the CSS syntax (on the same page as the docs for
StyleContext
.Note that the CSS syntax has certain special characters to delimit and represent elements in a selector (period, #, >, *…), so using these will make your widget impossible to match by name. Any combination of alphanumeric symbols, dashes and underscores will suffice.
- Parameters:
name – name for the widget
- set_opacity(opacity: float) None #
Request the
widget
to be rendered partially transparent.An opacity of 0 is fully transparent and an opacity of 1 is fully opaque.
Opacity works on both toplevel widgets and child widgets, although there are some limitations: For toplevel widgets, applying opacity depends on the capabilities of the windowing system. On X11, this has any effect only on X displays with a compositing manager, see
is_composited()
. On Windows and Wayland it should always work, although setting a window’s opacity after the window has been shown may cause some flicker.Note that the opacity is inherited through inclusion — if you set a toplevel to be partially translucent, all of its content will appear translucent, since it is ultimatively rendered on that toplevel. The opacity value itself is not inherited by child widgets (since that would make widgets deeper in the hierarchy progressively more translucent). As a consequence,
Popover
s and otherNative
widgets with their own surface will use their own opacity value, and thus by default appear non-translucent, even if they are attached to a toplevel that is translucent.- Parameters:
opacity – desired opacity, between 0 and 1
- set_overflow(overflow: Overflow) None #
Sets how
widget
treats content that is drawn outside the widget’s content area.See the definition of
Overflow
for details.This setting is provided for widget implementations and should not be used by application code.
The default value is
VISIBLE
.- Parameters:
overflow – desired overflow
- set_parent(parent: Widget) None #
Sets
parent
as the parent widget ofwidget
.This takes care of details such as updating the state and style of the child to reflect its new location and resizing the parent. The opposite function is
unparent
.This function is useful only when implementing subclasses of
GtkWidget
.- Parameters:
parent – parent widget
- set_receives_default(receives_default: bool) None #
Specifies whether
widget
will be treated as the default widget within its toplevel when it has the focus, even if another widget is the default.- Parameters:
receives_default – whether or not
widget
can be a default widget.
- set_sensitive(sensitive: bool) None #
Sets the sensitivity of a widget.
A widget is sensitive if the user can interact with it. Insensitive widgets are “grayed out” and the user can’t interact with them. Insensitive widgets are known as “inactive”, “disabled”, or “ghosted” in some other toolkits.
- Parameters:
sensitive –
True
to make the widget sensitive
- set_size_request(width: int, height: int) None #
Sets the minimum size of a widget.
That is, the widget’s size request will be at least
width
byheight
. You can use this function to force a widget to be larger than it normally would be.In most cases,
set_default_size
is a better choice for toplevel windows than this function; setting the default size will still allow users to shrink the window. Setting the size request will force them to leave the window at least as large as the size request.Note the inherent danger of setting any fixed size - themes, translations into other languages, different fonts, and user action can all change the appropriate size for a given widget. So, it’s basically impossible to hardcode a size that will always be correct.
The size request of a widget is the smallest size a widget can accept while still functioning well and drawing itself correctly. However in some strange cases a widget may be allocated less than its requested size, and in many cases a widget may be allocated more space than it requested.
If the size request in a given direction is -1 (unset), then the “natural” size request of the widget will be used instead.
The size request set here does not include any margin from the properties
margin_start
,margin_end
,margin_top
, andmargin_bottom
, but it does include pretty much all other padding or border properties set by any subclass ofGtkWidget
.- Parameters:
width – width
widget
should request, or -1 to unsetheight – height
widget
should request, or -1 to unset
- set_state_flags(flags: StateFlags, clear: bool) None #
Turns on flag values in the current widget state.
Typical widget states are insensitive, prelighted, etc.
This function accepts the values
DIR_LTR
andDIR_RTL
but ignores them. If you want to set the widget’s direction, useset_direction
.This function is for use in widget implementations.
- Parameters:
flags – State flags to turn on
clear – Whether to clear state before turning on
flags
- classmethod set_template_scope(scope: BuilderScope) None #
- Parameters:
scope
- set_tooltip_markup(markup: str | None = None) None #
Sets
markup
as the contents of the tooltip, which is marked up with Pango markup.This function will take care of setting the
has_tooltip
as a side effect, and of the default handler for thequery_tooltip
signal.See also
set_markup
.- Parameters:
markup – the contents of the tooltip for
widget
- set_tooltip_text(text: str | None = None) None #
Sets
text
as the contents of the tooltip.If
text
contains any markup, it will be escaped.This function will take care of setting
has_tooltip
as a side effect, and of the default handler for thequery_tooltip
signal.See also
set_text
.- Parameters:
text – the contents of the tooltip for
widget
- set_valign(align: Align) None #
Sets the vertical alignment of
widget
.- Parameters:
align – the vertical alignment
- set_vexpand(expand: bool) None #
Sets whether the widget would like any available extra vertical space.
See
set_hexpand
for more detail.- Parameters:
expand – whether to expand
- set_vexpand_set(set: bool) None #
Sets whether the vexpand flag will be used.
See
set_hexpand_set
for more detail.- Parameters:
set – value for vexpand-set property
- set_visible(visible: bool) None #
Sets the visibility state of
widget
.Note that setting this to
True
doesn’t mean the widget is actually viewable, seeget_visible
.- Parameters:
visible – whether the widget should be shown or not
- should_layout() bool #
Returns whether
widget
should contribute to the measuring and allocation of its parent.This is
False
for invisible children, but also for children that have their own surface.
- show() None #
Flags a widget to be displayed.
Any widget that isn’t shown will not appear on the screen.
Remember that you have to show the containers containing a widget, in addition to the widget itself, before it will appear onscreen.
When a toplevel container is shown, it is immediately realized and mapped; other shown widgets are realized and mapped when their toplevel container is realized and mapped.
Deprecated since version 4.10: Use
set_visible
instead
- size_allocate(allocation: Rectangle, baseline: int) None #
Allocates widget with a transformation that translates the origin to the position in
allocation
.This is a simple form of
allocate
.- Parameters:
allocation – position and size to be allocated to
widget
baseline – The baseline of the child, or -1
- snapshot_child(child: Widget, snapshot: Snapshot) None #
Snapshot the a child of
widget
.When a widget receives a call to the snapshot function, it must send synthetic
snapshot
calls to all children. This function provides a convenient way of doing this. A widget, when it receives a call to itssnapshot
function, callssnapshot_child()
once for each child, passing in thesnapshot
the widget received.snapshot_child()
takes care of translating the origin ofsnapshot
, and deciding whether the child needs to be snapshot.This function does nothing for children that implement
GtkNative
.- Parameters:
child – a child of
widget
snapshot –
GtkSnapshot
as passed to the widget. In particular, no calls totranslate()
or other transform calls should have been made.
- translate_coordinates(dest_widget: Widget, src_x: float, src_y: float) Tuple[bool, float, float] #
Translate coordinates relative to
src_widget
’s allocation to coordinates relative todest_widget
’s allocations.In order to perform this operation, both widget must share a common ancestor.
Deprecated since version 4.12: Use
compute_point()
instead- Parameters:
dest_widget – a
GtkWidget
src_x – X position relative to
src_widget
src_y – Y position relative to
src_widget
- trigger_tooltip_query() None #
Triggers a tooltip query on the display where the toplevel of
widget
is located.
- unmap() None #
Causes a widget to be unmapped if it’s currently mapped.
This function is only for use in widget implementations.
- unparent() None #
Dissociate
widget
from its parent.This function is only for use in widget implementations, typically in dispose.
- unrealize() None #
Causes a widget to be unrealized (frees all GDK resources associated with the widget).
This function is only useful in widget implementations.
- unset_state_flags(flags: StateFlags) None #
Turns off flag values for the current widget state.
See
set_state_flags
.This function is for use in widget implementations.
- Parameters:
flags – State flags to turn off
Properties#
- class Widget
-
- props.layout_manager: LayoutManager#
The type of the None singleton.
Signals#
- class Widget.signals
-
- direction_changed(previous_direction: TextDirection) None #
The type of the None singleton.
- Parameters:
previous_direction – the previous text direction of
widget
The type of the None singleton.
- Parameters:
direction – the direction of movement
- map() None #
Emitted when
widget
is going to be mapped.A widget is mapped when the widget is visible (which is controlled with
visible
) and all its parents up to the toplevel widget are also visible.The ::map signal can be used to determine whether a widget will be drawn, for instance it can resume an animation that was stopped during the emission of
unmap
.
- mnemonic_activate(group_cycling: bool) bool #
The type of the None singleton.
- Parameters:
group_cycling –
True
if there are other widgets with the same mnemonic
- move_focus(direction: DirectionType) None #
The type of the None singleton.
- Parameters:
direction – the direction of the focus move
- query_tooltip(x: int, y: int, keyboard_mode: bool, tooltip: Tooltip) bool #
The type of the None singleton.
- Parameters:
x – the x coordinate of the cursor position where the request has been emitted, relative to
widget
's left sidey – the y coordinate of the cursor position where the request has been emitted, relative to
widget
's topkeyboard_mode –
True
if the tooltip was triggered using the keyboardtooltip – a
GtkTooltip
- realize() None #
Emitted when
widget
is associated with aGdkSurface
.This means that
realize
has been called or the widget has been mapped (that is, it is going to be drawn).
- state_flags_changed(flags: StateFlags) None #
The type of the None singleton.
- Parameters:
flags – The previous state flags.
Virtual Methods#
- class Widget
- do_compute_expand(hexpand_p: bool, vexpand_p: bool) None #
- Computes whether a container should give this
widget extra space when possible.
- Parameters:
hexpand_p
vexpand_p
- do_contains(x: float, y: float) bool #
Tests if the point at (
x
,y
) is contained inwidget
.The coordinates for (
x
,y
) must be in widget coordinates, so (0, 0) is assumed to be the top left ofwidget
's content area.- Parameters:
x – X coordinate to test, relative to
widget
's originy – Y coordinate to test, relative to
widget
's origin
- do_css_changed(change: CssStyleChange) None #
The type of the None singleton.
- Parameters:
change
- do_direction_changed(previous_direction: TextDirection) None #
The type of the None singleton.
- Parameters:
previous_direction
- do_focus(direction: DirectionType) bool #
The type of the None singleton.
- Parameters:
direction
- do_get_request_mode() SizeRequestMode #
Gets whether the widget prefers a height-for-width layout or a width-for-height layout.
Single-child widgets generally propagate the preference of their child, more complex widgets need to request something either in context of their children or in context of their allocation capabilities.
- do_grab_focus() bool #
Causes
widget
to have the keyboard focus for theGtkWindow
it’s inside.If
widget
is not focusable, or itsgrab_focus
implementation cannot transfer the focus to a descendant ofwidget
that is focusable, it will not take focus andFalse
will be returned.Calling
grab_focus
on an already focused widget is allowed, should not have an effect, and returnTrue
.
- do_hide() None #
Reverses the effects of
show()
.This is causing the widget to be hidden (invisible to the user).
Deprecated since version 4.10: Use
set_visible
instead
- do_keynav_failed(direction: DirectionType) bool #
Emits the
::keynav-failed
signal on the widget.This function should be called whenever keyboard navigation within a single widget hits a boundary.
The return value of this function should be interpreted in a way similar to the return value of
child_focus
. WhenTrue
is returned, stay in the widget, the failed keyboard navigation is OK and/or there is nowhere we can/should move the focus to. WhenFalse
is returned, the caller should continue with keyboard navigation outside the widget, e.g. by callingchild_focus
on the widget’s toplevel.The default
keynav_failed
handler returnsFalse
forTAB_FORWARD
andTAB_BACKWARD
. For the other values ofGtkDirectionType
it returnsTrue
.Whenever the default handler returns
True
, it also callserror_bell
to notify the user of the failed keyboard navigation.A use case for providing an own implementation of ::keynav-failed (either by connecting to it or by overriding it) would be a row of
Entry
widgets where the user should be able to navigate the entire row with the cursor keys, as e.g. known from user interfaces that require entering license keys.- Parameters:
direction – direction of focus movement
- do_map() None #
Causes a widget to be mapped if it isn’t already.
This function is only for use in widget implementations.
- do_measure(orientation: Orientation, for_size: int) Tuple[int, int, int, int] #
Measures
widget
in the orientationorientation
and for the givenfor_size
.As an example, if
orientation
isHORIZONTAL
andfor_size
is 300, this functions will compute the minimum and natural width ofwidget
if it is allocated at a height of 300 pixels.See GtkWidget’s geometry management section for a more details on implementing
GtkWidgetClass.measure()
.- Parameters:
orientation – the orientation to measure
for_size – Size for the opposite of
orientation
, i.e. iforientation
isHORIZONTAL
, this is the height the widget should be measured with. TheVERTICAL
case is analogous. This way, both height-for-width and width-for-height requests can be implemented. If no size is known, -1 can be passed.
- do_mnemonic_activate(group_cycling: bool) bool #
Emits the ::mnemonic-activate signal.
See
mnemonic_activate
.- Parameters:
group_cycling –
True
if there are other widgets with the same mnemonic
- do_move_focus(direction: DirectionType) None #
The type of the None singleton.
- Parameters:
direction
- do_query_tooltip(x: int, y: int, keyboard_tooltip: bool, tooltip: Tooltip) bool #
The type of the None singleton.
- Parameters:
x
y
keyboard_tooltip
tooltip
- do_realize() None #
Creates the GDK resources associated with a widget.
Normally realization happens implicitly; if you show a widget and all its parent containers, then the widget will be realized and mapped automatically.
Realizing a widget requires all the widget’s parent widgets to be realized; calling this function realizes the widget’s parents in addition to
widget
itself. If a widget is not yet inside a toplevel window when you realize it, bad things will happen.This function is primarily used in widget implementations, and isn’t very useful otherwise. Many times when you think you might need it, a better approach is to connect to a signal that will be called after the widget is realized automatically, such as
realize
.
- do_set_focus_child(child: Widget | None = None) None #
Set
child
as the current focus child ofwidget
.This function is only suitable for widget implementations. If you want a certain widget to get the input focus, call
grab_focus
on it.- Parameters:
child – a direct child widget of
widget
orNone
to unset the focus child ofwidget
- do_show() None #
Flags a widget to be displayed.
Any widget that isn’t shown will not appear on the screen.
Remember that you have to show the containers containing a widget, in addition to the widget itself, before it will appear onscreen.
When a toplevel container is shown, it is immediately realized and mapped; other shown widgets are realized and mapped when their toplevel container is realized and mapped.
Deprecated since version 4.10: Use
set_visible
instead
- do_size_allocate(width: int, height: int, baseline: int) None #
- Called to set the allocation, if the widget does
not have a layout manager.
- Parameters:
width
height
baseline
- do_state_flags_changed(previous_state_flags: StateFlags) None #
The type of the None singleton.
- Parameters:
previous_state_flags
- do_system_setting_changed(settings: SystemSetting) None #
The type of the None singleton.
- Parameters:
settings
- do_unmap() None #
Causes a widget to be unmapped if it’s currently mapped.
This function is only for use in widget implementations.