Expand description
Rust GTK 4 bindings
The project website is here.
Rust bindings of GTK 4, part of gtk4-rs.
This library contains safe Rust bindings for GTK 4, a multi-platform GUI toolkit. It is a part of gtk-rs.
Most of this documentation is generated from the C API. Until all parts of the documentation have been reviewed there will be incongruities with the actual Rust API.
For a gentle introduction to gtk-rs we recommend the online book GUI development with Rust and GTK 4.
See also:
- gtk-rs project overview
- General
GLib
family types and object system overview - GTK documentation
- GTK Visual Index
Minimum supported Rust version
Currently, the minimum supported Rust version is 1.63.0
.
“Hello, World!” example program
GTK needs to be initialized before use by calling init
. Creating an
Application
will call init
for you.
The gtk4
crate is usually renamed to gtk
. You can find an example in
the features section for how to do this globally in your Cargo.toml
.
use gtk4 as gtk;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow};
fn main() {
let app = Application::builder()
.application_id("org.example.HelloWorld")
.build();
app.connect_activate(|app| {
// We create the main window.
let window = ApplicationWindow::builder()
.application(app)
.default_width(320)
.default_height(200)
.title("Hello, World!")
.build();
// Show the window.
window.show();
});
app.run();
}
The main loop
In a typical GTK application you set up the UI, assign signal handlers and run the main event loop.
use gtk4 as gtk;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Button};
fn main() {
let application = Application::builder()
.application_id("com.example.FirstGtkApp")
.build();
application.connect_activate(|app| {
let window = ApplicationWindow::builder()
.application(app)
.title("First GTK Program")
.default_width(350)
.default_height(70)
.build();
let button = Button::with_label("Click me!");
button.connect_clicked(|_| {
eprintln!("Clicked!");
});
window.set_child(Some(&button));
window.show();
});
application.run();
}
Threads
GTK is not thread-safe. Accordingly, none of this crate’s structs implement
Send
or Sync
.
The thread where init
was called is considered the main thread. OS X has
its own notion of the main thread and init
must be called on that thread.
After successful initialization, calling any gtk
or gdk
functions (including init
) from other threads will panic
.
Any thread can schedule a closure to be run by the main loop on the main
thread via glib::idle_add
or
glib::timeout_add
. While
working with GTK you might need the glib::idle_add_local
or glib::timeout_add_local
version without the
Send
bound. Those may only be called from the main thread.
Panics
The gtk
and gdk
crates have some run-time safety and contract
checks.
-
Any constructor or free function will panic if called before
init
or on a non-main thread. -
Any
&str
or&Path
parameter with an interior null (\0
) character will cause a panic. -
Some functions will panic if supplied out-of-range integer parameters. All such cases will be documented individually but they are not yet.
-
A panic in a closure that handles signals or in any other closure passed to a
gtk
function will abort the process.
Features
Library versions
By default this crate provides only GTK 4.0 APIs. You can access additional
functionality by selecting one of the v4_2
, v4_4
, etc. features.
Cargo.toml
example:
[dependencies.gtk]
package = "gtk4"
version = "0.x.y"
features = ["v4_2"]
Take care when choosing the version to target: some of your users might not have easy access to the latest ones. The higher the version, the fewer users will have it installed.
Documentation
- The Rust API Stable/Development
- Book Stable/Development
- Examples
- The C API
- GTK Installation Instructions
Using
We recommend using crates from crates.io, as demonstrated here.
If you want to track the bleeding edge, use the git dependency instead:
[dependencies]
gtk = { git = "https://github.com/gtk-rs/gtk4-rs.git", package = "gtk4" }
Avoid mixing versioned and git crates like this:
# This will not compile
[dependencies]
gdk = {version = "0.1", package = "gdk4"}
gtk = { git = "https://github.com/gtk-rs/gtk4-rs.git", package = "gtk4" }
Features
Feature | Description |
---|---|
v4_10 | Enable the new APIs part of the to be released GTK 4.10 |
v4_8 | Enable the new APIs part of GTK 4.8 |
v4_6 | Enable the new APIs part of GTK 4.6 |
v4_4 | Enable the new APIs part of GTK 4.4 |
v4_2 | Enable the new APIs part of GTK 4.2 |
gnome_43 | Enable all version feature flags of this crate and its dependencies to match the GNOME 43 SDK |
gnome_42 | Enable all version feature flags of this crate and its dependencies to match the GNOME 42 SDK |
unsafe-assume-initialized | Disable checks that gtk is initialized, for use in C ABI libraries |
xml_validation | Enable xml_validation feature of gtk4-macros |
See Also
License
The Rust bindings of gtk4 are available under the MIT License, please refer to it.
Re-exports
pub use ffi;
pub use cairo;
pub use gdk;
pub use gdk_pixbuf;
pub use gio;
pub use glib;
pub use graphene;
pub use gsk;
pub use pango;
pub use subclass::widget::TemplateChild;
Modules
Structs
ATContext
is an abstract class provided by GTK to communicate to
platform-specific assistive technologies API.AboutDialog
offers a simple way to display information about
a program.Accessible
is an interface for describing UI elements for
Assistive Technologies.v4_10
Actionable
interface provides a convenient way of asscociating
widgets with actions.ShortcutAction
that calls gtk_widget_activate().Adjustment
is a model for a numeric value.v4_10
AlertDialog
object collects the arguments that
are needed to present a message to the user.ShortcutTrigger
that combines two triggers.AppChooser
is an interface for widgets which allow the user to
choose an application.AppChooserButton
lets the user select an application.AppChooserDialog
shows a AppChooserWidget
inside a Dialog
.AppChooserWidget
is a widget for selecting applications.Application
is a high-level API for writing applications.Application
.AspectFrame
preserves the aspect ratio of its child.AssistantPage
is an auxiliary object used by `GtkAssistant.BinLayout
is a LayoutManager
subclass useful for create “bins” of
widgets.Bitset
.BookmarkList
is a list model that wraps GBookmarkFile
.BoolFilter
evaluates a boolean Expression
to determine whether to include items.BuilderListItemFactory
is a ListItemFactory
that creates
widgets by instantiating Builder
UI templates.BuilderScope
that can bind Rust callbacks.BuilderScope
is an interface to provide language binding support
to Builder
.Button
widget is generally used to trigger a callback function that is
called when the button is pressed.ShortcutAction
that invokes a callback.CellRenderer
sEditable
for editable text widgets
Interface for widgets that can be used for editing cellsLayoutManager
for layout manager delegate objects
An interface for packing cellsDropDown
instead
Renders a combobox in a cellProgressBar
instead
Renders numbers as progress barsSpinButton
instead
Renders a spin button in a cellSpinner
instead
Renders a spinning animation in a cellInscription
or Label
instead
Renders text in a cellToggleButton
instead
Renders a toggle button in a cellBox
instead
A widget displaying a single row of a GtkTreeModelCenterBox
arranges three children in a row, keeping the middle child
centered as well as possible.CenterLayout
is a layout manager that manages up to three children.CheckButton
places a label next to an indicator.GClosure
to compute the value from
its parameters.ColorDialogButton
instead
The ColorButton
allows to open a color chooser dialog to change
the color.ColorDialog
and ColorDialogButton
instead of widgets implementing ColorChooser
ColorChooser
is an interface that is implemented by widgets
for choosing colors.ColorDialog
instead
A dialog for choosing a color.ColorChooserWidget
is deprecated.
The ColorChooserWidget
widget lets the user select a color.v4_10
ColorDialog
object collects the arguments that
are needed to present a color chooser dialog to the
user, such as a title for the dialog and whether it
should be modal.v4_10
ColorDialogButton
is a wrapped around a ColorDialog
and allows to open a color chooser dialog to change the color.ColumnView
presents a large dynamic list of items using multiple columns
with headers.ColumnViewColumn
represents the columns being added to ColumnView
.v4_10
ColumnViewSorter
is a sorter implementation that
is geared towards the needs of ColumnView
.DropDown
with a StringList
instead
A ComboBoxText
is a simple variant of ComboBox
for text-only
use cases.Expression
.Constraint
describes a constraint between attributes of two widgets,
expressed as a linear equation.ConstraintGuide
is an invisible layout element in a
ConstraintLayout
.LayoutChild
subclass for children in a ConstraintLayout
.ConstraintTarget
interface is implemented by objects that
can be used as source or target in Constraint
s.CssProvider
is an object implementing the StyleProvider
interface
for CSS.CustomFilter
determines whether to include items with a callback.CustomSorter
is a Sorter
implementation that sorts via a callback
function.DirectoryList
is a list model that wraps g_file_enumerate_children_async().DragSource
is an event controller to initiate Drag-And-Drop operations.DrawingArea
is a widget that allows drawing with cairo.DropControllerMotion
is an event controller tracking
the pointer during Drag-and-Drop operations.DropTarget
is an event controller to receive Drag-and-Drop operations.DropTargetAsync
is an event controller to receive Drag-and-Drop
operations, asynchronously.EditableLabel
is a label that allows users to
edit the text by switching to an “edit mode”.EmojiChooser
is used by text widgets such as Entry
or
TextView
to let users insert Emoji characters.EntryBuffer
hold the text displayed in a Text
widget.EntryCompletion
is an auxiliary object to provide completion functionality
for Entry
.EventController
is the base class for event controllers.EventControllerFocus
is an event controller to keep track of
keyboard focus.EventControllerKey
is an event controller that provides access
to key events.EventControllerLegacy
is an event controller that provides raw
access to the event stream.EventControllerMotion
is an event controller tracking the pointer
position.EventControllerScroll
is an event controller that handles scroll
events.EventControllerScroll
.EveryFilter
matches an item when each of its filters matches.Expression
provides a way to describe references to values.Expression
.FileDialog
instead
FileChooser
is an interface that can be implemented by file
selection widgets.FileDialog
instead
FileChooserDialog
is a dialog suitable for use with
“File Open” or “File Save” commands.FileDialog
instead
FileChooserNative
is an abstraction of a dialog suitable
for use with “File Open” or “File Save as” commands.FileChooserWidget
is deprecated
FileChooserWidget
is a widget for choosing files.v4_10
FileDialog
object collects the arguments that
are needed to present a file chooser dialog to the
user, such as a title for the dialog and whether it
should be modal.FileFilter
filters files by name or mime type.v4_10
FileLauncher
object collects the arguments that are needed to open a uri
with an application.Filter
object describes the filtering to be performed by a
FilterListModel
.FilterListModel
is a list model that filters the elements of
the underlying model according to a Filter
.FixedLayout
is a layout manager which can place child widgets
at fixed positions.LayoutChild
subclass for children in a FixedLayout
.FlattenListModel
is a list model that concatenates other list models.FlowBoxChild
is the kind of widget that can be added to a FlowBox
.FontDialogButton
instead
The FontButton
allows to open a font chooser dialog to change
the font.FontDialog
and FontDialogButton
instead
FontChooser
is an interface that can be implemented by widgets
for choosing fonts.FontDialog
instead
The FontChooserDialog
widget is a dialog for selecting a font.FontChooser
.FontChooserWidget
is deprecated.
The FontChooserWidget
widget lets the user select a font.v4_10
FontDialog
object collects the arguments that
are needed to present a font chooser dialog to the
user, such as a title for the dialog and whether it
should be modal.v4_10
FontDialogButton
is wrapped around a FontDialog
and allows to open a font chooser dialog to change the font.GestureClick
is a Gesture
implementation for clicks.GestureDrag
is a Gesture
implementation for drags.GestureLongPress
is a Gesture
for long presses.GesturePan
is a Gesture
for pan gestures.GestureRotate
is a Gesture
for 2-finger rotations.GestureSingle
is a GtkGestures
subclass optimized for singe-touch
and mouse gestures.GestureStylus
is a Gesture
specific to stylus input.GestureSwipe
is a Gesture
for swipe gestures.GestureZoom
is a Gesture
for 2-finger pinch/zoom gestures.GridLayout
is a layout manager which arranges child widgets in
rows and columns.LayoutChild
subclass for children in a GridLayout
.IMContextSimple
is an input method supporting table-based input methods.IMMulticontext
is an input method context supporting multiple,
switchable input methods.IconTheme
.v4_8
Inscription
is a widget to show text in a predefined area.ShortcutTrigger
that triggers when a specific keyval and modifiers are pressed.LayoutChild
is the base class for objects that are meant to hold
layout properties.LinkButton
is a button with a hyperlink.ListBoxRow
is the kind of widget that can be added to a ListBox
.ListItemFactory
creates widgets for the items taken from a GListModel
.LockButton
is a widget to obtain and revoke authorizations
needed to operate the controls.MapListModel
maps the items in a list model to different items.MediaControls
is a widget to show controls for a video.MediaFile
implements MediaStream
for files.MediaStream
is the integration point for media playback inside GTK.MenuButton
widget is used to display a popup when clicked.AlertDialog
instead
MessageDialog
presents a dialog with some message text.ShortcutAction
that calls gtk_widget_mnemonic_activate().ShortcutTrigger
that triggers when a specific mnemonic is pressed.MountOperation
is an implementation of GMountOperation
.MultiFilter
is the base class for filters that combine multiple filters.MultiSelection
is a SelectionModel
that allows selecting multiple
elements.MultiSorter
combines multiple sorters by trying them
in turn.ShortcutAction
that activates an action by name.Native
is the interface implemented by all widgets that have
their own gdk::Surface
.Dialog
.ShortcutTrigger
that never triggers.NoSelection
is a SelectionModel
that does not allow selecting
anything.NotebookPage
is an auxiliary object used by Notebook
.ShortcutAction
that does nothing.NumericSorter
is a Sorter
that compares numbers.GObject
value in a Expression
.Orientable
interface is implemented by all widgets that can be
oriented horizontally or vertically.Overlay
is a container which contains a single main child, on top
of which it can place “overlay” widgets.OverlayLayout
is the layout manager used by Overlay
.LayoutChild
subclass for children in a OverlayLayout
.PadController
is an event controller for the pads found in drawing
tablets.PageSetupUnixDialog
implements a page setup dialog for platforms
which don’t provide a native page setup dialog, like Unix.GParamSpec
for properties holding a Expression
.PasswordEntry
is an entry that has been tailored for entering secrets.EntryBuffer
that locks the underlying memory to prevent it
from being swapped to disk.WidgetExt::pick()
.Picture
widget displays a gdk::Paintable
.PopoverMenu
is a subclass of Popover
that implements menu
behavior.PopoverMenuBar
presents a horizontal bar of items that pop
up popover menus when clicked.PrintContext
encapsulates context information that is required when
drawing pages for printing.PrintOperation
is the high-level, portable printing API.PrintOperationPreview
is the interface that is used to
implement print preview.PrintSettings
object represents the settings of a print dialog in
a system-independent way.PrintUnixDialog
implements a print dialog for platforms
which don’t provide a native print dialog, like Unix.ProgressBar
is typically used to display the progress of a long
running operation.GObject
property value in a Expression
.RecentInfo
contains the metadata associated with an item in the
recently used files list.RecentManager
manages and looks up recently used files.Requisition
represents the desired size of a widget. See
GtkWidget’s geometry management section for
more information.ScaleButton
provides a button which pops up a scale widget.Scrollable
is an interface for widgets with native scrolling ability.ScrolledWindow
is a container that makes its child scrollable.SearchEntry
is an entry widget that has been tailored for use
as a search entry.SelectionFilterModel
is a list model that presents the selection from
a SelectionModel
.SelectionModel
is an interface that add support for selection to list models.ShortcutAction
encodes an action that can be triggered by a
keyboard shortcut.ShortcutController
is an event controller that manages shortcuts.ShortcutLabel
displays a single keyboard shortcut or gesture.ShortcutManager
interface is used to implement
shortcut scopes.ShortcutTrigger
tracks how a Shortcut
should be activated.ShortcutsGroup
represents a group of related keyboard shortcuts
or gestures.ShortcutsSection
collects all the keyboard shortcuts and gestures
for a major application mode.ShortcutsShortcut
represents a single keyboard shortcut or gesture
with a short text.ShortcutsWindow
shows information about the keyboard shortcuts
and gestures of an application.Shortcut
Action that emits a signal.SignalListItemFactory
is a ListItemFactory
that emits signals
to to manage listitems.SingleSelection
is a SelectionModel
that allows selecting a single
item.SliceListModel
is a list model that presents a slice of another model.Snapshot
assists in creating gsk::RenderNode
s for widgets.GListModel
that sorts the elements of an underlying model
according to a Sorter
.SpinButton
is an ideal way to allow the user to set the
value of some attribute.StackSidebar
uses a sidebar to switch between Stack
pages.StackSwitcher
shows a row of buttons to switch between Stack
pages.StringFilter
determines whether to include items by comparing
strings to a fixed search term.StringList
is a list model that wraps an array of strings.StringObject
is the type of items in a StringList
.StringSorter
is a Sorter
that compares strings.Widget
where applicable; otherwise, there is no replacement for querying the
style machinery. Stylable UI elements should use widgets.
StyleContext
stores styling information affecting a widget.StyleProvider
is an interface for style information used by
StyleContext
.SymbolicPaintable
is an interface that support symbolic colors in
paintables.TextView
.TextChildAnchor
is a spot in a TextBuffer
where child widgets can
be “anchored”.TextBuffer
.TextBuffer
.TextBuffer
TextBuffer
.ToggleButton
is a button which remains “pressed-in” when
clicked.DropTarget
to implement a drop destination
Interface for Drag-and-Drop destinations in TreeView
.DragSource
to implement a drag source
Interface for Drag-and-Drop destinations in TreeView
.TreeExpander
is a widget that provides an expander for a list.TreeListModel
is a list model that can create child models on demand.TreeListRow
is used by TreeListModel
to represent items.TreeListRowSorter
is a special-purpose sorter that will apply a given
sorter to the levels in a tree.gio::ListModel
instead
The tree interface used by GtkTreeViewFilterListModel
instead.
A TreeModel
which hides parts of an underlying tree modelTreeModel
.SortListModel
instead
A GtkTreeModel which makes an underlying tree model sortableTreePath
refers to a position, not a fixed row). Create a
new GtkTreeRowReference with gtk_tree_row_reference_new().SelectionModel
instead
The selection object for GtkTreeViewSortListModel
to wrap your list model instead
The interface for sortable models used by GtkTreeViewTreeListModel
instead
A tree-like data structure that can be used with the TreeView
.ListView
for lists, and ColumnView
for tabular lists
A widget for displaying both trees and listsColumnView
and ColumnViewColumn
instead of TreeView
to show a tabular list
A visible column in a TreeView
widgetVideo
is a widget to show a MediaStream
with media controls.VolumeButton
is a ScaleButton
subclass tailored for
volume control.WidgetPaintable
is a gdk::Paintable
that displays the contents
of a widget.WindowControls
shows window frame controls.WindowGroup
makes group of windows behave like separate applications.WindowHandle
is a titlebar area widget.Enums
AccessibleProperty::Autocomplete
accessible property.AccessibleState::Invalid
accessible state.Accessible
.Accessible
.Accessible
implementation.AccessibleProperty::Sort
accessible property.Accessible
.AccessibleState::Pressed
accessible state.Assistant
.Builder
.Dialog
.property::CellRendererAccel::accel-mode
.v4_10
StringSorter
turns strings into sort keys to
compare them.Constraint
.v4_8
ScrolledWindow
v4_10
GTK_DIALOG_ERROR
domain that can be returned
by async dialog functions.Editable
properties.gdk::EventSequence
in a Gesture
.FileChooser
is being used to open existing files
or to save to a possibly new file.FileChooser
functions.v4_10
IconTheme
operations.Label
widget.LevelBar
contents should be rendered.MessageDialog
.v4_6
Notebook
.GesturePan
.EventController
for handling events
targeting other widgets.EventController
.RecentManager
operationsRevealer
widget is shown or hidden.Shortcut
s added to a
ShortcutController
get handled.Sorter
may produce.Stack
widget.v4_6
vfunc::Gtk::SymbolicPaintable::snapshot_symbolic
.vfunc::Gtk::Widget::system_setting_changed
vfunc.GtkTextView::extend-selection
signal to customize the selection.TextView
for the purpose of customized
drawing with the ::snapshot_layer vfunc.TextView
.Autosize
are inefficient for large views, and
can make columns appear choppy.Constants
GListModel
.StyleProvider
for application-specific style information.Settings
.$XDG_CONFIG_HOME/gtk-4.0/gtk.css
.Statics
LevelBar
.LevelBar
.LevelBar
.Functions
libtool
.pango::Language
for the default language
currently in effect.gtk_init
and gtk_init_check
from automatically calling
setlocale (LC_ALL, "")
.Printer
s.libtool
.true
if GTK has been initialized.true
if GTK has been initialized and this is the main thread.PageSetup
is identical to the passed in @page_setup, otherwise it contains the
modifications done in the dialog.Spinner
).
The state StateFlags::CHECKED
determines whether there is
activity going on.CheckButton
).TreeView
and Expander
) in the area
defined by @x, @y, @width, @height. The state StateFlags::CHECKED
determines whether the expander is collapsed or expanded.StateFlags::CHECKED
state will determine whether the option is on or off, and
StateFlags::INCONSISTENT
whether it should be marked as undefined.Accessible
has @property set.Accessible
has @relation set.GtkAccessible:accessible-role
of the accessible
is @role.Accessible
has @state set.GTK_TYPE_TREE_ROW_DATA
.