Crate gtk

Source
Expand description

§Rust GTK 3 bindings

This project is UNMAINTAINED. Please take a look at gtk4-rs instead!

Project site

Rust bindings and wrappers for GTK 3, part of gtk3-rs, a multi-platform GUI toolkit. It is a part of gtk-rs.

GTK 3.22.30 is the lowest supported version for the underlying library.

§Minimum supported Rust version

Currently, the minimum supported Rust version is 1.70.0.

§Building

gtk expects GTK, GLib and Cairo development files to be installed on your system. See the GTK installation page.

§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/gtk3-rs.git" }

Avoid mixing versioned and git crates like this:

# This will not compile
[dependencies]
gtk = "0.13"
gtk = { git = "https://github.com/gtk-rs/gtk3-rs.git" }

§“Hello, World!” example program

//! GTK needs to be initialized before use by calling init. Creating an Application will call init for you.

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 win = ApplicationWindow::builder()
            .application(app)
            .default_width(320)
            .default_height(200)
            .title("Hello, World!")
            .build();

        // Don't forget to make all widgets visible.
        win.show_all();
    });

    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 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.add(&button);

        window.show_all();
    });

    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 3.22.30 APIs. You can access additional functionality by selecting one of the v3_24, etc. features.

Cargo.toml example:

[dependencies.gtk]
version = "0.x.y"
features = ["v3_24"]

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

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.

Generate the docs:

> RUSTFLAGS="--cfg docsrs" cargo doc

(if the installed GTK+ version is lower than 3.16, adjust the feature name accordingly).

§Contribute

Contributor you’re welcome!

See the general bindings documentation.

Most of the bindings (src/auto) are generated by gir using this configuration file. After editing Gir.toml the sources can be regenerated with

> make gir

When opening a PR please put the changes to the src/auto directory in a separate commit.

You may also wish to run cargo clippy -- -D warnings and check that you’re clean because otherwise you may be surprised when CI fails.

§See Also

But also:

§License

gtk is available under the MIT License, please refer to it.

Re-exports§

pub use ffi;
pub use atk;
pub use cairo;
pub use gdk;
pub use gdk_pixbuf;
pub use gio;
pub use glib;
pub use pango;

Modules§

builders
Builder pattern types.
prelude
Traits and essential types intended for blanket imports.
subclass
xlib

Structs§

AboutDialog
AccelFlags
AccelGroup
AccelLabel
ActionBar
Actionable
Adjustment
Allocation
AppChooser
AppChooserButton
AppChooserDialog
AppChooserWidget
Application
ApplicationInhibitFlags
ApplicationWindow
AspectFrame
Assistant
Bin
Border
Box
Buildable
Builder
Button
ButtonBox
Calendar
CalendarDisplayOptions
CellArea
CellAreaBox
CellAreaContext
CellEditable
CellLayout
CellRenderer
CellRendererAccel
CellRendererCombo
CellRendererPixbuf
CellRendererProgress
CellRendererSpin
CellRendererSpinner
CellRendererState
CellRendererText
CellRendererToggle
CellView
CheckButton
CheckMenuItem
Clipboard
ColorButton
ColorChooser
ColorChooserDialog
ColorChooserWidget
ComboBox
ComboBoxText
Container
CssProvider
CssSection
DestDefaults
Dialog
DialogFlags
DrawingArea
Editable
Entry
EntryBuffer
EntryCompletion
EventBox
EventController
Expander
FileChooser
FileChooserButton
FileChooserDialog
FileChooserNative
FileChooserWidget
FileFilter
FileFilterFlags
FileFilterInfo
Fixed
FlowBox
FlowBoxChild
FontButton
FontChooser
FontChooserDialog
FontChooserWidget
Frame
GLArea
Gesture
GestureDrag
GestureLongPress
GestureMultiPress
GesturePan
GestureRotate
GestureSingle
GestureSwipe
GestureZoom
Grid
HeaderBar
IMContext
IMContextSimple
IMMulticontext
IconInfo
IconLookupFlags
IconTheme
IconView
Image
InfoBar
InputHints
Invisible
JunctionSides
Label
Layout
LevelBar
LinkButton
ListBox
ListBoxRow
ListStore
LockButton
Menu
MenuBar
MenuButton
MenuItem
MenuShell
MenuToolButton
MessageDialog
Misc
ModelButton
MountOperation
NativeDialog
Notebook
OffscreenWindow
Orientable
Overlay
PadActionEntry
PadController
PageRange
PageSetup
Paned
PaperSize
PlacesOpenFlags
PlacesSidebar
Pluggdk_backend="x11"
Popover
PopoverMenu
PrintContext
PrintOperation
PrintOperationPreview
PrintSettings
ProgressBar
RadioButton
RadioMenuItem
RadioToolButton
Range
RecentChooser
RecentChooserDialog
RecentChooserMenu
RecentChooserWidget
RecentData
RecentFilter
RecentFilterFlags
RecentInfo
RecentManager
Rectangle
RegionFlags
Requisition
Revealer
Scale
ScaleButton
Scrollable
Scrollbar
ScrolledWindow
SearchBar
SearchEntry
SelectionData
Separator
SeparatorMenuItem
SeparatorToolItem
Settings
ShortcutLabel
ShortcutsGroup
ShortcutsSection
ShortcutsShortcut
ShortcutsWindow
SizeGroup
Socketgdk_backend="x11"
SpinButton
Spinner
Stack
StackSidebar
StackSwitcher
StateFlags
Statusbar
StyleContext
StyleContextPrintFlags
StyleProperties
StyleProvider
Switch
TargetEntry
TargetFlags
TargetList
TextAttributes
TextBuffer
TextChildAnchor
TextIter
TextMark
TextSearchFlags
TextTag
TextTagTable
TextView
TickCallbackId
ToggleButton
ToggleToolButton
ToolButton
ToolItem
ToolItemGroup
ToolPalette
ToolPaletteDragTargets
ToolShell
Toolbar
Tooltip
TreeDragDest
TreeDragSource
TreeIter
TreeModel
TreeModelFilter
TreeModelFlags
TreeModelSort
TreePath
TreeRowReference
TreeSelection
TreeSortable
TreeStore
TreeView
TreeViewColumn
Viewport
VolumeButton
Widget
WidgetPath
Window
WindowGroup

Enums§

Align
ArrowType
AssistantPageType
BaselinePosition
BorderStyle
BuilderError
ButtonBoxStyle
ButtonRole
ButtonsType
CellRendererAccelMode
CellRendererMode
CornerType
CssProviderError
CssSectionType
DeleteType
DirectionType
DragResult
EntryIconPosition
EventSequenceState
FileChooserAction
FileChooserConfirmation
FileChooserError
IconSize
IconThemeError
IconViewDropPosition
ImageType
InputPurpose
Justification
LevelBarMode
License
MenuDirectionType
MessageType
MovementStep
NotebookTab
NumberUpLayout
Orientation
PackDirection
PackType
PadActionType
PageOrientation
PageSet
PanDirection
PolicyType
PopoverConstraint
PositionType
PrintDuplex
PrintError
PrintOperationAction
PrintOperationResult
PrintPages
PrintQuality
PrintStatus
PropagationPhase
RecentChooserError
RecentManagerError
RecentSortType
ReliefStyle
ResizeMode
ResponseType
RevealerTransitionType
ScrollStep
ScrollType
ScrollablePolicy
SelectionMode
SensitivityType
ShadowType
ShortcutType
SizeGroupMode
SizeRequestMode
SortColumn
SortType
SpinButtonUpdatePolicy
SpinType
StackTransitionType
TextDirection
TextExtendSelection
TextViewLayer
TextWindowType
ToolbarStyle
TreeViewColumnSizing
TreeViewDropPosition
TreeViewGridLines
Unit
WidgetHelpType
WindowPosition
WindowType
WrapMode

Constants§

STYLE_PROVIDER_PRIORITY_APPLICATION
STYLE_PROVIDER_PRIORITY_FALLBACK
STYLE_PROVIDER_PRIORITY_SETTINGS
STYLE_PROVIDER_PRIORITY_THEME
STYLE_PROVIDER_PRIORITY_USER

Statics§

LEVEL_BAR_OFFSET_FULL
LEVEL_BAR_OFFSET_HIGH
LEVEL_BAR_OFFSET_LOW
PAPER_NAME_A3
PAPER_NAME_A4
PAPER_NAME_A5
PAPER_NAME_B5
PAPER_NAME_EXECUTIVE
PAPER_NAME_LEGAL
PAPER_NAME_LETTER
PRINT_SETTINGS_COLLATE
PRINT_SETTINGS_DEFAULT_SOURCE
PRINT_SETTINGS_DITHER
PRINT_SETTINGS_DUPLEX
PRINT_SETTINGS_FINISHINGS
PRINT_SETTINGS_MEDIA_TYPE
PRINT_SETTINGS_NUMBER_UP
PRINT_SETTINGS_NUMBER_UP_LAYOUT
PRINT_SETTINGS_N_COPIES
PRINT_SETTINGS_ORIENTATION
PRINT_SETTINGS_OUTPUT_BASENAME
PRINT_SETTINGS_OUTPUT_BIN
PRINT_SETTINGS_OUTPUT_DIR
PRINT_SETTINGS_OUTPUT_FILE_FORMAT
PRINT_SETTINGS_OUTPUT_URI
PRINT_SETTINGS_PAGE_RANGES
PRINT_SETTINGS_PAGE_SET
PRINT_SETTINGS_PAPER_FORMAT
PRINT_SETTINGS_PAPER_HEIGHT
PRINT_SETTINGS_PAPER_WIDTH
PRINT_SETTINGS_PRINTER
PRINT_SETTINGS_PRINTER_LPI
PRINT_SETTINGS_PRINT_PAGES
PRINT_SETTINGS_QUALITY
PRINT_SETTINGS_RESOLUTION
PRINT_SETTINGS_RESOLUTION_X
PRINT_SETTINGS_RESOLUTION_Y
PRINT_SETTINGS_REVERSE
PRINT_SETTINGS_SCALE
PRINT_SETTINGS_USE_COLOR
PRINT_SETTINGS_WIN32_DRIVER_EXTRA
PRINT_SETTINGS_WIN32_DRIVER_VERSION
STYLE_CLASS_ACCELERATOR
STYLE_CLASS_ARROW
STYLE_CLASS_BACKGROUND
STYLE_CLASS_BOTTOM
STYLE_CLASS_BUTTON
STYLE_CLASS_CALENDAR
STYLE_CLASS_CELL
STYLE_CLASS_CHECK
STYLE_CLASS_COMBOBOX_ENTRY
STYLE_CLASS_CONTEXT_MENU
STYLE_CLASS_CSD
STYLE_CLASS_CURSOR_HANDLE
STYLE_CLASS_DEFAULT
STYLE_CLASS_DESTRUCTIVE_ACTION
STYLE_CLASS_DIM_LABEL
STYLE_CLASS_DND
STYLE_CLASS_DOCK
STYLE_CLASS_ENTRY
STYLE_CLASS_ERROR
STYLE_CLASS_EXPANDER
STYLE_CLASS_FLAT
STYLE_CLASS_FRAME
STYLE_CLASS_GRIP
STYLE_CLASS_HEADER
STYLE_CLASS_HIGHLIGHT
STYLE_CLASS_HORIZONTAL
STYLE_CLASS_IMAGE
STYLE_CLASS_INFO
STYLE_CLASS_INLINE_TOOLBAR
STYLE_CLASS_INSERTION_CURSOR
STYLE_CLASS_LABEL
STYLE_CLASS_LEFT
STYLE_CLASS_LEVEL_BAR
STYLE_CLASS_LINKED
STYLE_CLASS_LIST
STYLE_CLASS_LIST_ROW
STYLE_CLASS_MARK
STYLE_CLASS_MENU
STYLE_CLASS_MENUBAR
STYLE_CLASS_MENUITEM
STYLE_CLASS_MESSAGE_DIALOG
STYLE_CLASS_MONOSPACE
STYLE_CLASS_NEEDS_ATTENTION
STYLE_CLASS_NOTEBOOK
STYLE_CLASS_OSD
STYLE_CLASS_OVERSHOOT
STYLE_CLASS_PANE_SEPARATOR
STYLE_CLASS_PAPER
STYLE_CLASS_POPOVER
STYLE_CLASS_POPUP
STYLE_CLASS_PRIMARY_TOOLBAR
STYLE_CLASS_PROGRESSBAR
STYLE_CLASS_PULSE
STYLE_CLASS_QUESTION
STYLE_CLASS_RADIO
STYLE_CLASS_RAISED
STYLE_CLASS_READ_ONLY
STYLE_CLASS_RIGHT
STYLE_CLASS_RUBBERBAND
STYLE_CLASS_SCALE
STYLE_CLASS_SCALE_HAS_MARKS_ABOVE
STYLE_CLASS_SCALE_HAS_MARKS_BELOW
STYLE_CLASS_SCROLLBAR
STYLE_CLASS_SCROLLBARS_JUNCTION
STYLE_CLASS_SEPARATOR
STYLE_CLASS_SIDEBAR
STYLE_CLASS_SLIDER
STYLE_CLASS_SPINBUTTON
STYLE_CLASS_SPINNER
STYLE_CLASS_STATUSBAR
STYLE_CLASS_SUBTITLE
STYLE_CLASS_SUGGESTED_ACTION
STYLE_CLASS_TITLE
STYLE_CLASS_TITLEBAR
STYLE_CLASS_TOOLBAR
STYLE_CLASS_TOOLTIP
STYLE_CLASS_TOP
STYLE_CLASS_TOUCH_SELECTION
STYLE_CLASS_TROUGH
STYLE_CLASS_UNDERSHOOT
STYLE_CLASS_VERTICAL
STYLE_CLASS_VIEW
STYLE_CLASS_WARNING
STYLE_CLASS_WIDE
STYLE_PROPERTY_BACKGROUND_COLOR
STYLE_PROPERTY_BACKGROUND_IMAGE
STYLE_PROPERTY_BORDER_COLOR
STYLE_PROPERTY_BORDER_RADIUS
STYLE_PROPERTY_BORDER_STYLE
STYLE_PROPERTY_BORDER_WIDTH
STYLE_PROPERTY_COLOR
STYLE_PROPERTY_FONT
STYLE_PROPERTY_MARGIN
STYLE_PROPERTY_PADDING

Traits§

EditableSignals
OverlaySignals
SpinButtonSignals

Functions§

accel_groups_activate
accel_groups_from_object
accelerator_get_default_mod_mask
accelerator_get_label
accelerator_get_label_with_keycode
accelerator_name
accelerator_name_with_keycode
accelerator_parse
accelerator_parse_with_keycode
accelerator_set_default_mod_mask
accelerator_valid
binary_age
bindings_activate
bindings_activate_event
cairo_should_draw_window
cairo_transform_to_window
check_version
current_event
current_event_device
current_event_state
current_event_time
debug_flags
default_language
device_grab_add
device_grab_remove
disable_setlocale
event_widget
events_pending
false_
grab_get_current
init
Tries to initialize GTK+.
interface_age
is_initialized
Returns true if GTK has been initialized.
is_initialized_main_thread
Returns true if GTK has been initialized and this is the main thread.
locale_direction
main
main_do_event
main_iteration
main_iteration_do
main_level
main_quit
major_version
micro_version
minor_version
print_run_page_setup_dialog
print_run_page_setup_dialog_async
propagate_event
render_activity
render_arrow
render_background
render_background_get_clip
render_check
render_expander
render_extension
render_focus
render_frame
render_frame_gap
render_handle
render_icon
render_icon_surface
render_insertion_cursor
render_layout
render_line
render_option
render_slider
rgb_to_hsv
selection_add_target
selection_clear_targets
selection_convert
selection_owner_set
selection_owner_set_for_display
selection_remove_all
set_debug_flags
set_initialized
Informs this crate that GTK has been initialized and the current thread is the main one.
show_uri_on_window
targets_include_image
targets_include_rich_text
targets_include_text
targets_include_uri
test_find_label
test_find_sibling
test_find_widget
test_register_all_types
test_widget_send_key
test_widget_wait_for_draw
tree_get_row_drag_data
tree_set_row_drag_data
true_