Label
Superclasses: Widget
, InitiallyUnowned
, Object
Implemented Interfaces: Accessible
, AccessibleText
, Buildable
, ConstraintTarget
The GtkLabel
widget displays a small amount of text.
As the name implies, most labels are used to label another widget
such as a Button
.
CSS nodes
label
├── [selection]
├── [link]
┊
╰── [link]
GtkLabel
has a single CSS node with the name label. A wide variety
of style classes may be applied to labels, such as .title, .subtitle,
.dim-label, etc. In the GtkShortcutsWindow
, labels are used with the
.keycap style class.
If the label has a selection, it gets a subnode with name selection.
If the label has links, there is one subnode per link. These subnodes carry the link or visited state depending on whether they have been visited. In this case, label node also gets a .link style class.
GtkLabel as GtkBuildable
The GtkLabel implementation of the GtkBuildable interface supports a
custom <attributes>
element, which supports any number of <attribute>
elements. The <attribute>
element has attributes named “name“, “value“,
“start“ and “end“ and allows you to specify Attribute
values for this label.
An example of a UI definition fragment specifying Pango attributes:
<object class="GtkLabel">
<attributes>
<attribute name="weight" value="PANGO_WEIGHT_BOLD"/>
<attribute name="background" value="red" start="5" end="10"/>
</attributes>
</object>
The start and end attributes specify the range of characters to which the Pango attribute applies. If start and end are not specified, the attribute is applied to the whole text. Note that specifying ranges does not make much sense with translatable attributes. Use markup embedded in the translatable content instead.
Accessibility
GtkLabel
uses the LABEL
role.
Mnemonics
Labels may contain “mnemonics”. Mnemonics are underlined characters in the
label, used for keyboard navigation. Mnemonics are created by providing a
string with an underscore before the mnemonic character, such as "_File"
,
to the functions new_with_mnemonic
or
set_text_with_mnemonic
.
Mnemonics automatically activate any activatable widget the label is
inside, such as a Button
; if the label is not inside the
mnemonic’s target widget, you have to tell the label about the target
using set_mnemonic_widget
.
Here’s a simple example where the label is inside a button:
// Pressing Alt+H will activate this button
GtkWidget *button = gtk_button_new ();
GtkWidget *label = gtk_label_new_with_mnemonic ("_Hello");
gtk_button_set_child (GTK_BUTTON (button), label);
There’s a convenience function to create buttons with a mnemonic label already inside:
// Pressing Alt+H will activate this button
GtkWidget *button = gtk_button_new_with_mnemonic ("_Hello");
To create a mnemonic for a widget alongside the label, such as a
Entry
, you have to point the label at the entry with
set_mnemonic_widget
:
// Pressing Alt+H will focus the entry
GtkWidget *entry = gtk_entry_new ();
GtkWidget *label = gtk_label_new_with_mnemonic ("_Hello");
gtk_label_set_mnemonic_widget (GTK_LABEL (label), entry);
Markup (styled text)
To make it easy to format text in a label (changing colors, fonts, etc.), label text can be provided in a simple markup format:
Here’s how to create a label with a small font:
GtkWidget *label = gtk_label_new (NULL);
gtk_label_set_markup (GTK_LABEL (label), "<small>Small text</small>");
(See the Pango manual for complete documentation] of available
tags, parse_markup
)
The markup passed to set_markup
must be valid; for example,
literal <
, >
and &
characters must be escaped as <
, >
, and &
.
If you pass text obtained from the user, file, or a network to
set_markup
, you’ll want to escape it with
markup_escape_text
or markup_printf_escaped
.
Markup strings are just a convenient way to set the AttrList
on a label; set_attributes
may be a simpler way to set
attributes in some cases. Be careful though; AttrList
tends
to cause internationalization problems, unless you’re applying attributes
to the entire string (i.e. unless you set the range of each attribute
to [0, %G_MAXINT
)). The reason is that specifying the start_index and
end_index for a Attribute
requires knowledge of the exact
string being displayed, so translations will cause problems.
Selectable labels
Labels can be made selectable with set_selectable
.
Selectable labels allow the user to copy the label contents to
the clipboard. Only labels that contain useful-to-copy information—such
as error messages—should be made selectable.
Text layout
A label can contain any number of paragraphs, but will have performance problems if it contains more than a small number. Paragraphs are separated by newlines or other paragraph separators understood by Pango.
Labels can automatically wrap text if you call set_wrap
.
set_justify
sets how the lines in a label align
with one another. If you want to set how the label as a whole aligns
in its available space, see the halign
and
valign
properties.
The width_chars
and max_width_chars
properties can be used to control the size allocation of ellipsized or
wrapped labels. For ellipsizing labels, if either is specified (and less
than the actual text size), it is used as the minimum width, and the actual
text size is used as the natural width of the label. For wrapping labels,
width-chars is used as the minimum width, if specified, and max-width-chars
is used as the natural width. Even if max-width-chars specified, wrapping
labels will be rewrapped to use all of the available width.
Links
GTK supports markup for clickable hyperlinks in addition to regular Pango
markup. The markup for links is borrowed from HTML, using the <a>
with
“href“, “title“ and “class“ attributes. GTK renders links similar to the
way they appear in web browsers, with colored, underlined text. The “title“
attribute is displayed as a tooltip on the link. The “class“ attribute is
used as style class on the CSS node for the link.
An example of inline links looks like this:
const char *text =
"Go to the "
"<a href=\"https://www.gtk.org\" title=\"<i>Our</i> website\">"
"GTK website</a> for more...";
GtkWidget *label = gtk_label_new (NULL);
gtk_label_set_markup (GTK_LABEL (label), text);
It is possible to implement custom handling for links and their tooltips
with the activate_link
signal and the
get_current_uri
function.
Constructors
- class Label
- classmethod new(str: str | None = None) Widget
Creates a new label with the given text inside it.
You can pass
None
to get an empty label widget.- Parameters:
str – The text of the label
- classmethod new_with_mnemonic(str: str | None = None) Widget
Creates a new
GtkLabel
, containing the text instr
.If characters in
str
are preceded by an underscore, they are underlined. If you need a literal underscore character in a label, use ‘__
’ (two underscores). The first underlined character represents a keyboard accelerator called a mnemonic. The mnemonic key can be used to activate another widget, chosen automatically, or explicitly usingset_mnemonic_widget
.If
set_mnemonic_widget
is not called, then the first activatable ancestor of theGtkLabel
will be chosen as the mnemonic widget. For instance, if the label is inside a button or menu item, the button or menu item will automatically become the mnemonic widget and be activated by the mnemonic.- Parameters:
str – The text of the label, with an underscore in front of the mnemonic character
Methods
- class Label
- get_attributes() AttrList | None
Gets the label’s attribute list.
This is the
AttrList
that was set on the label usingset_attributes
, if any. This function does not reflect attributes that come from the label’s markup (seeset_markup
). If you want to get the effective attributes for the label, usepango_layout_get_attributes (gtk_label_get_layout (self))
.
- get_current_uri() str | None
Returns the URI for the currently active link in the label.
The active link is the one under the mouse pointer or, in a selectable label, the link in which the text cursor is currently positioned.
This function is intended for use in a
activate_link
handler or for use in aquery_tooltip
handler.
- get_ellipsize() EllipsizeMode
Returns the ellipsizing position of the label.
See
set_ellipsize
.
Gets the extra menu model of
label
.See
set_extra_menu
.
- get_justify() Justification
Returns the justification of the label.
See
set_justify
.
- get_label() str
Fetches the text from a label.
The returned text includes any embedded underlines indicating mnemonics and Pango markup. (See
get_text
).
- get_layout() Layout
Gets the
PangoLayout
used to display the label.The layout is useful to e.g. convert text positions to pixel positions, in combination with
get_layout_offsets
. The returned layout is owned by thelabel
so need not be freed by the caller. Thelabel
is free to recreate its layout at any time, so it should be considered read-only.
- get_layout_offsets() tuple[int, int]
Obtains the coordinates where the label will draw its
PangoLayout
.The coordinates are useful to convert mouse events into coordinates inside the
Layout
, e.g. to take some action if some part of the label is clicked. Remember when using theLayout
functions you need to convert to and from pixels usingPIXELS()
orSCALE
.
- get_lines() int
Gets the number of lines to which an ellipsized, wrapping label should be limited.
See
set_lines
.
- get_max_width_chars() int
Retrieves the desired maximum width of
label
, in characters.See
set_width_chars
.
- get_mnemonic_keyval() int
Return the mnemonic accelerator.
If the label has been set so that it has a mnemonic key this function returns the keyval used for the mnemonic accelerator. If there is no mnemonic set up it returns
GDK_KEY_VoidSymbol
.
- get_mnemonic_widget() Widget | None
Retrieves the target of the mnemonic (keyboard shortcut) of this label.
See
set_mnemonic_widget
.
- get_natural_wrap_mode() NaturalWrapMode
Returns line wrap mode used by the label.
Added in version 4.6.
- get_tabs() TabArray | None
Gets the tabs for
self
.The returned array will be
None
if “standard” (8-space) tabs are used. Free the return value withfree
.Added in version 4.8.
- get_text() str
Fetches the text from a label.
The returned text is as it appears on screen. This does not include any embedded underlines indicating mnemonics or Pango markup. (See
get_label
)
- get_use_markup() bool
Returns whether the label’s text is interpreted as Pango markup.
See
set_use_markup
.
- get_use_underline() bool
Returns whether an embedded underlines in the label indicate mnemonics.
See
set_use_underline
.
- get_width_chars() int
Retrieves the desired width of
label
, in characters.See
set_width_chars
.
- get_wrap_mode() WrapMode
Returns line wrap mode used by the label.
See
set_wrap_mode
.
- select_region(start_offset: int, end_offset: int) None
Selects a range of characters in the label, if the label is selectable.
See
set_selectable
. If the label is not selectable, this function has no effect. Ifstart_offset
orend_offset
are -1, then the end of the label will be substituted.- Parameters:
start_offset – start offset (in characters not bytes)
end_offset – end offset (in characters not bytes)
- set_attributes(attrs: AttrList | None = None) None
Apply attributes to the label text.
The attributes set with this function will be applied and merged with any other attributes previously effected by way of the
use_underline
oruse_markup
properties. While it is not recommended to mix markup strings with manually set attributes, if you must; know that the attributes will be applied to the label after the markup string is parsed.- Parameters:
attrs – a
AttrList
- set_ellipsize(mode: EllipsizeMode) None
Sets the mode used to ellipsize the text.
The text will be ellipsized if there is not enough space to render the entire string.
- Parameters:
mode – a
PangoEllipsizeMode
Sets a menu model to add when constructing the context menu for
label
.- Parameters:
model – a
GMenuModel
- set_justify(jtype: Justification) None
Sets the alignment of the lines in the text of the label relative to each other.
LEFT
is the default value when the widget is first created withnew
. If you instead want to set the alignment of the label as a whole, useset_halign
instead.set_justify
has no effect on labels containing only a single line.- Parameters:
jtype – a
GtkJustification
- set_label(str: str) None
Sets the text of the label.
The label is interpreted as including embedded underlines and/or Pango markup depending on the values of the
use_underline
anduse_markup
properties.- Parameters:
str – the new text to set for the label
- set_lines(lines: int) None
Sets the number of lines to which an ellipsized, wrapping label should be limited.
This has no effect if the label is not wrapping or ellipsized. Set this to -1 if you don’t want to limit the number of lines.
- Parameters:
lines – the desired number of lines, or -1
- set_markup(str: str) None
Sets the labels text and attributes from markup.
The string must be marked up with Pango markup (see
parse_markup
).If the
str
is external data, you may need to escape it withmarkup_escape_text()
ormarkup_printf_escaped()
:GtkWidget *self = gtk_label_new (NULL); const char *str = "..."; const char *format = "<span style=\"italic\">\``%s``</span>"; char *markup; markup = g_markup_printf_escaped (format, str); gtk_label_set_markup (GTK_LABEL (self), markup); g_free (markup);
This function will set the
use_markup
property toTrue
as a side effect.If you set the label contents using the
label
property you should also ensure that you set theuse_markup
property accordingly.See also:
set_text
- Parameters:
str – a markup string
- set_markup_with_mnemonic(str: str) None
Sets the labels text, attributes and mnemonic from markup.
Parses
str
which is marked up with Pango markup (seeparse_markup
), setting the label’s text and attribute list based on the parse results. If characters instr
are preceded by an underscore, they are underlined indicating that they represent a keyboard accelerator called a mnemonic.The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using
set_mnemonic_widget
.- Parameters:
str – a markup string
- set_max_width_chars(n_chars: int) None
Sets the desired maximum width in characters of
label
ton_chars
.- Parameters:
n_chars – the new desired maximum width, in characters.
- set_mnemonic_widget(widget: Widget | None = None) None
Associate the label with its mnemonic target.
If the label has been set so that it has a mnemonic key (using i.e.
set_markup_with_mnemonic
,set_text_with_mnemonic
,new_with_mnemonic
or theuse_underline
property) the label can be associated with a widget that is the target of the mnemonic. When the label is inside a widget (like aButton
or aNotebook
tab) it is automatically associated with the correct widget, but sometimes (i.e. when the target is aEntry
next to the label) you need to set it explicitly using this function.The target widget will be accelerated by emitting the
mnemonic_activate
signal on it. The default handler for this signal will activate the widget if there are no mnemonic collisions and toggle focus between the colliding widgets otherwise.- Parameters:
widget – the target
GtkWidget
, orNone
to unset
- set_natural_wrap_mode(wrap_mode: NaturalWrapMode) None
Select the line wrapping for the natural size request.
This only affects the natural size requested, for the actual wrapping used, see the
wrap_mode
property.Added in version 4.6.
- Parameters:
wrap_mode – the line wrapping mode
- set_selectable(setting: bool) None
Makes text in the label selectable.
Selectable labels allow the user to select text from the label, for copy-and-paste.
- Parameters:
setting –
True
to allow selecting text in the label
- set_single_line_mode(single_line_mode: bool) None
Sets whether the label is in single line mode.
- Parameters:
single_line_mode –
True
if the label should be in single line mode
- set_tabs(tabs: TabArray | None = None) None
Sets the default tab stops for paragraphs in
self
.Added in version 4.8.
- Parameters:
tabs – tabs as a
PangoTabArray
- set_text(str: str) None
Sets the text within the
GtkLabel
widget.It overwrites any text that was there before.
This function will clear any previously set mnemonic accelerators, and set the
use_underline
property toFalse
as a side effect.This function will set the
use_markup
property toFalse
as a side effect.See also:
set_markup
- Parameters:
str – The text you want to set
- set_text_with_mnemonic(str: str) None
Sets the label’s text from the string
str
.If characters in
str
are preceded by an underscore, they are underlined indicating that they represent a keyboard accelerator called a mnemonic. The mnemonic key can be used to activate another widget, chosen automatically, or explicitly usingset_mnemonic_widget
.- Parameters:
str – a string
- set_use_markup(setting: bool) None
Sets whether the text of the label contains markup.
See
set_markup
.- Parameters:
setting –
True
if the label’s text should be parsed for markup.
- set_use_underline(setting: bool) None
Sets whether underlines in the text indicate mnemonics.
- Parameters:
setting –
True
if underlines in the text indicate mnemonics
- set_width_chars(n_chars: int) None
Sets the desired width in characters of
label
ton_chars
.- Parameters:
n_chars – the new desired width, in characters.
- set_wrap(wrap: bool) None
Toggles line wrapping within the
GtkLabel
widget.True
makes it break lines if text exceeds the widget’s size.False
lets the text get cut off by the edge of the widget if it exceeds the widget size.Note that setting line wrapping to
True
does not make the label wrap at its parent container’s width, because GTK widgets conceptually can’t make their requisition depend on the parent container’s size. For a label that wraps at a specific position, set the label’s width usingset_size_request
.- Parameters:
wrap – the setting
- set_wrap_mode(wrap_mode: WrapMode) None
Controls how line wrapping is done.
This only affects the label if line wrapping is on. (See
set_wrap
) The default is%PANGO_WRAP_WORD
which means wrap on word boundaries.For sizing behavior, also consider the
natural_wrap_mode
property.- Parameters:
wrap_mode – the line wrapping mode
Properties
- class Label
-
- props.ellipsize: EllipsizeMode
The preferred place to ellipsize the string, if the label does not have enough room to display the entire string.
Note that setting this property to a value other than
%PANGO_ELLIPSIZE_NONE
has the side-effect that the label requests only enough space to display the ellipsis “…”. In particular, this means that ellipsizing labels do not work well in notebook tabs, unless thetab_expand
child property is set toTrue
. Other ways to set a label’s width areset_size_request
andset_width_chars
.
A menu model whose contents will be appended to the context menu.
- props.justify: Justification
The alignment of the lines in the text of the label, relative to each other.
This does not affect the alignment of the label within its allocation. See
xalign
for that.
- props.label: str
The contents of the label.
If the string contains Pango markup (see
parse_markup
), you will have to set theuse_markup
property toTrue
in order for the label to display the markup attributes. See alsoset_markup
for a convenience function that sets both this property and theuse_markup
property at the same time.If the string contains underlines acting as mnemonics, you will have to set the
use_underline
property toTrue
in order for the label to display them.
- props.lines: int
The number of lines to which an ellipsized, wrapping label should be limited.
This property has no effect if the label is not wrapping or ellipsized. Set this property to -1 if you don’t want to limit the number of lines.
- props.max_width_chars: int
The desired maximum width of the label, in characters.
If this property is set to -1, the width will be calculated automatically.
See the section on text layout for details of how
width_chars
andmax_width_chars
determine the width of ellipsized and wrapped labels.
- props.natural_wrap_mode: NaturalWrapMode
Select the line wrapping for the natural size request.
This only affects the natural size requested. For the actual wrapping used, see the
wrap_mode
property.The default is
INHERIT
, which inherits the behavior of thewrap_mode
property.Added in version 4.6.
- props.single_line_mode: bool
Whether the label is in single line mode.
In single line mode, the height of the label does not depend on the actual text, it is always set to ascent + descent of the font. This can be an advantage in situations where resizing the label because of text changes would be distracting, e.g. in a statusbar.
- props.use_markup: bool
True
if the text of the label includes Pango markup.See
parse_markup
.
- props.use_underline: bool
True
if the text of the label indicates a mnemonic with an _ before the mnemonic character.
- props.width_chars: int
The desired width of the label, in characters.
If this property is set to -1, the width will be calculated automatically.
See the section on text layout for details of how
width_chars
andmax_width_chars
determine the width of ellipsized and wrapped labels.
- props.wrap_mode: WrapMode
Controls how the line wrapping is done.
This only affects the formatting if line wrapping is on (see the
wrap
property). The default is%PANGO_WRAP_WORD
, which means wrap on word boundaries.For sizing behavior, also consider the
natural_wrap_mode
property.
Signals
- class Label.signals
- activate_current_link() None
Gets emitted when the user activates a link in the label.
The ::activate-current-link is a keybinding signal.
Applications may also emit the signal with
signal_emit_by_name()
if they need to control activation of URIs programmatically.The default bindings for this signal are all forms of the Enter key.
- activate_link(uri: str) bool
Gets emitted to activate a URI.
Applications may connect to it to override the default behaviour, which is to call
launch
.- Parameters:
uri – the URI that is activated
- copy_clipboard() None
Gets emitted to copy the selection to the clipboard.
The ::copy-clipboard signal is a keybinding signal.
The default binding for this signal is Ctrl`+:kbd:`c.
- move_cursor(step: MovementStep, count: int, extend_selection: bool) None
Gets emitted when the user initiates a cursor movement.
The ::move-cursor signal is a keybinding signal. If the cursor is not visible in
entry
, this signal causes the viewport to be moved instead.Applications should not connect to it, but may emit it with
signal_emit_by_name()
if they need to control the cursor programmatically.The default bindings for this signal come in two variants, the variant with the Shift modifier extends the selection, the variant without the Shift modifier does not. There are too many key combinations to list them all here.
←, →, ↑, ↓ move by individual characters/lines
Ctrl`+:kbd:`←, etc. move by words/paragraphs
Home and End move to the ends of the buffer
- Parameters:
step – the granularity of the move, as a
GtkMovementStep
count – the number of
step
units to moveextend_selection –
True
if the move should extend the selection