Documentation
¶
Overview ¶
Package slint provides Go bindings for the Slint declarative UI toolkit.
UIs are written in Slint's .slint markup language and driven from Go. This package compiles .slint markup at runtime (via Slint's interpreter), creates component instances, and lets you read and write properties, handle callbacks, back models, load images, and run timers — all from Go.
Threading ¶
Slint is thread-affine. Compile, Create, property/callback access, and Run must all happen on a single OS thread. Lock it at program start:
func init() { runtime.LockOSThread() }
To touch the UI from another goroutine, post work with InvokeFromEventLoop.
A minimal program ¶
package main
import (
_ "embed"
"runtime"
"github.com/rileylov/go-slint"
)
func init() { runtime.LockOSThread() }
//go:embed app.slint
var ui string
func main() {
app, err := slint.Compile(ui, slint.WithStyle("fluent"))
if err != nil {
panic(err)
}
defer app.Close()
win, err := app.Create("AppWindow")
if err != nil {
panic(err)
}
defer win.Close()
win.OnCallback("clicked", func([]any) any {
n, _ := win.Int("counter")
win.Set("counter", n+1)
return nil
})
win.Run()
}
Value mapping ¶
Properties and callback arguments/returns convert between Slint and Go as:
void <-> nil
int / float / length / angle <-> float64
bool <-> bool
string <-> string
struct / anonymous object <-> map[string]any
enum <-> [Enum]{Type, Value}
color / solid brush <-> [Color]
gradient brush <-> [Gradient] (linear or radial)
image <-> *[Image] (write; load via [LoadImage])
array / model <-> []any (read) or [*ModelHandle] (write)
Build a writable model with NewSliceModel (or NewModel for a custom Model) and assign it to an array/model property; mutating it notifies Slint.
Resource ownership ¶
A few types own native (Slint/Rust) memory the Go garbage collector can't reclaim, so release them explicitly — ideally with defer:
- Compilation.Close after compiling;
- Instance.Close for each window (also released when the window closes);
- [Image.Close] for images you create or read back from a property;
- [Timer.Close] for timers.
Forgetting these leaks native memory. During development, run with the GOSLINT_DEV environment variable set: goslint then warns to stderr whenever such an object is garbage-collected without having been released — a quick way to catch a missing Free/Close. (It only warns; it never frees off the UI thread, which would be unsafe.)
See the examples directory for runnable apps (hello, counter, todo, clock, interop, chartstress) and CLAUDE.md for the architecture.
The package overview lives in doc.go.
Index ¶
- Constants
- func As[T any](v any) (T, error)
- func ClearTranslator()
- func ClipboardText() string
- func InitHeadless() error
- func InvokeFromEventLoop(fn func()) error
- func LiveReload(path, component string, bind func(*Instance) error, opts ...Option) error
- func MockElapsedTime(ms uint64)
- func Quit() error
- func Run() error
- func RunUntilQuit() error
- func SetClipboardText(s string) error
- func SetTranslator(fn func(msgid string) string) error
- func SingleShot(intervalMs uint64, fn func())
- func Version() string
- type Callback
- type Color
- type Compilation
- type DataTransfer
- type Diagnostic
- type DiagnosticError
- type Enum
- type FileLoader
- type Gradient
- type GradientStop
- type Image
- func LoadImage(path string) (*Image, error)
- func NewImage(src image.Image) (*Image, error)
- func NewImageFromData(data []byte, format string) (*Image, error)
- func NewImageFromSVG(data []byte) (*Image, error)
- func NewImageRGB(pix []byte, w, h int) (*Image, error)
- func NewImageRGBA(pix []byte, w, h int) (*Image, error)
- type Instance
- func (i *Instance) Bool(name string) (bool, error)
- func (i *Instance) Close()
- func (i *Instance) Float(name string) (float64, error)
- func (i *Instance) Get(name string) (any, error)
- func (i *Instance) GetGlobal(global, name string) (any, error)
- func (i *Instance) Hide() error
- func (i *Instance) Int(name string) (int, error)
- func (i *Instance) Invoke(name string, args ...any) (any, error)
- func (i *Instance) InvokeGlobal(global, name string, args ...any) (any, error)
- func (i *Instance) OnCallback(name string, fn Callback) error
- func (i *Instance) OnCloseRequested(handler func() (allowClose bool))
- func (i *Instance) OnGlobalCallback(global, name string, fn Callback) error
- func (i *Instance) RegisterFontFromMemory(data []byte) error
- func (i *Instance) RegisterFontFromPath(path string) error
- func (i *Instance) RequestClose()
- func (i *Instance) RequestRedraw()
- func (i *Instance) Run() error
- func (i *Instance) ScaleFactor() float32
- func (i *Instance) Set(name string, v any) error
- func (i *Instance) SetFullscreen(on bool)
- func (i *Instance) SetGlobal(global, name string, v any) error
- func (i *Instance) SetMaximized(on bool)
- func (i *Instance) SetMinimized(on bool)
- func (i *Instance) SetWindowPosition(x, y int)
- func (i *Instance) SetWindowSize(w, h int)
- func (i *Instance) Show() error
- func (i *Instance) Snapshot() (*image.NRGBA, error)
- func (i *Instance) SnapshotRGBA() (pix []byte, w, h int, err error)
- func (i *Instance) Str(name string) (string, error)
- func (i *Instance) WindowPosition() (x, y int)
- func (i *Instance) WindowSize() (w, h int)
- type LiveModel
- type Model
- type ModelHandle
- type Option
- type SliceModel
- func (s *SliceModel) Append(v any)
- func (s *SliceModel) Close()
- func (s *SliceModel) Handle() *ModelHandle
- func (s *SliceModel) Len() int
- func (s *SliceModel) RemoveAt(row int)
- func (s *SliceModel) RowCount() int
- func (s *SliceModel) RowData(row int) any
- func (s *SliceModel) SetRowData(row int, v any)
- type Timer
Constants ¶
const ( TimerSingleShot = slintsys.TimerSingleShot TimerRepeated = slintsys.TimerRepeated )
Timer modes.
Variables ¶
This section is empty.
Functions ¶
func As ¶ added in v0.18.0
As converts a dynamic property/callback value to the typed T, returning a clear error instead of panicking when the value isn't that type. The generated typed getters build on it, so an unexpected value surfaces as an error — matching the dynamic API (Instance.Int, etc.) rather than a panic mid-getter.
func ClearTranslator ¶ added in v0.4.0
func ClearTranslator()
ClearTranslator removes the translator so `@tr` shows its source strings again.
func ClipboardText ¶ added in v0.4.0
func ClipboardText() string
ClipboardText returns the system clipboard's text ("" if empty or unavailable). The clipboard is provided by the backend, so call it once a window exists.
func InitHeadless ¶
func InitHeadless() error
InitHeadless installs the headless testing backend (mock time, no real windows). Intended for tests; call once per process on the UI thread.
func InvokeFromEventLoop ¶
func InvokeFromEventLoop(fn func()) error
InvokeFromEventLoop posts fn to run once on the event-loop (UI) thread. Safe to call from any goroutine; it is the only safe way to touch UI state (properties, models, callbacks) from a background goroutine.
func LiveReload ¶
LiveReload compiles the .slint file at path, creates component (or the last exported one if component is ""), wires it with bind, shows it, and then hot-reloads whenever any .slint file beside it changes on disk — recompiling and swapping the content into the SAME window in place (no new window, no Go rebuild). It runs the event loop and returns when the window is closed.
It's the engine behind `goslint dev`: because the interpreter loads markup at runtime, editing a .slint and saving updates the UI live. bind is re-invoked on each reload with the fresh instance, so wire your callbacks/properties there (note: property state resets on reload). Call runtime.LockOSThread first, as with any Slint program.
func MockElapsedTime ¶
func MockElapsedTime(ms uint64)
MockElapsedTime advances the headless backend's mock clock by ms milliseconds.
func Run ¶
func Run() error
Run enters the Slint event loop until the last window closes or Quit is called. It blocks and must run on the UI thread.
func RunUntilQuit ¶ added in v0.4.0
func RunUntilQuit() error
RunUntilQuit is like Run but does not exit when the last window closes — it runs until Quit. Use it for multi-window apps that open and close windows dynamically. Show at least one window before calling it.
func SetClipboardText ¶ added in v0.4.0
SetClipboardText sets the system clipboard text.
func SetTranslator ¶ added in v0.4.0
SetTranslator installs a function that translates `@tr("…")` source strings at runtime, and re-renders existing translations. Call it again to switch languages (e.g. with a different lookup table); the handler returns the original string when it has no translation. Call on the UI thread, after a window/backend exists.
func SingleShot ¶
func SingleShot(intervalMs uint64, fn func())
SingleShot fires fn once after the given number of milliseconds.
Types ¶
type Callback ¶
type Callback = slintsys.CallbackFunc
Callback is a Go handler invoked by Slint. Its args and return use the same Go value representation as properties (float64, bool, string, map[string]any, Enum, nil, ...).
type Compilation ¶
type Compilation struct {
// contains filtered or unexported fields
}
Compilation is a successfully compiled set of components.
func Compile ¶
func Compile(source string, opts ...Option) (*Compilation, error)
Compile compiles `.slint` source. It returns a *DiagnosticError if the source has errors.
func CompileFS ¶ added in v0.6.0
CompileFS compiles the `.slint` file `entry` from `fsys` (typically an embed.FS), resolving every relative import through the same filesystem — so a multi-file component compiles entirely from embedded bytes, with nothing on disk and no temp files. Import paths are resolved relative to the FS root (i.e. as embedded), which matches `//go:embed` when the embedding .go sits alongside the markup. This is the self-contained compile path for generated code and for hand-rolled stateful reload.
//go:embed app.slint components/card.slint var ui embed.FS comp, err := slint.CompileFS(ui, "app.slint")
func CompileFile ¶
func CompileFile(path string, opts ...Option) (*Compilation, error)
CompileFile compiles a `.slint` file from disk.
func CompileSource ¶ added in v0.3.0
func CompileSource(path, source string, opts ...Option) (*Compilation, error)
CompileSource compiles markup from a string while treating it as if it lived at `path`, so relative imports (and @image-url) resolve from path's directory on disk. Generated typed code uses this so multi-file components work; for a single embedded file with no relative imports, plain Compile is enough.
func (*Compilation) Close ¶
func (c *Compilation) Close()
Close releases the compilation's resources.
func (*Compilation) ComponentNames ¶
func (c *Compilation) ComponentNames() []string
ComponentNames lists the exported components.
func (*Compilation) Create ¶
func (c *Compilation) Create(name string) (*Instance, error)
Create instantiates the named component.
func (*Compilation) CreateWithWindow ¶ added in v0.5.0
func (c *Compilation) CreateWithWindow(name string, winOwner *Instance) (*Instance, error)
CreateWithWindow instantiates the named component reusing winOwner's window, so the new content renders in the same on-screen window. Used by live reload to swap the UI in place instead of opening a new window.
type DataTransfer ¶ added in v0.8.0
type DataTransfer = slintsys.DataTransfer
DataTransfer is a drag-and-drop payload — Slint 1.17's `data-transfer` type carried by a DragArea. go-slint bridges its plain-text content: return one from a callback wired to produce a `data-transfer` (e.g. `DragArea.data: Api.makeData(...)`), and read it from a DropArea's DropEvent (`event.data`). A non-empty payload is required for a drag to start.
func NewDataTransfer ¶ added in v0.8.0
func NewDataTransfer(text string) DataTransfer
NewDataTransfer builds a drag payload carrying text (e.g. an item id or JSON).
type Diagnostic ¶ added in v0.11.0
type Diagnostic = slintsys.Diagnostic
Diagnostic is a single compiler message (error, warning, or note).
type DiagnosticError ¶
type DiagnosticError struct {
Diagnostics []Diagnostic
}
DiagnosticError reports one or more compiler errors.
func (*DiagnosticError) Error ¶
func (e *DiagnosticError) Error() string
Error implements the error interface, listing the compiler diagnostics.
type Enum ¶
Enum is the Go representation of a Slint enumeration value (e.g. Enum{Type: "TextHorizontalAlignment", Value: "center"}). Structs are represented as map[string]any.
type FileLoader ¶ added in v0.3.0
type FileLoader = slintsys.FileLoader
FileLoader resolves a `.slint` import path to source; ok=false means "not found" (normal include-path/disk resolution then proceeds). Builtins like std-widgets are handled internally and never passed to it.
type Gradient ¶ added in v0.2.0
Gradient is a gradient `brush` value (linear by default, or Radial); set it on a brush/color property, or read one back from Get. GradientStop is one stop.
type GradientStop ¶ added in v0.2.0
type GradientStop = slintsys.GradientStop
GradientStop is one stop of a Gradient: Pos in 0..=1 with a Color.
type Image ¶
Image is a loaded image; assign it to an `image` property and Close it when done.
TODO(v1.0): make Image (and Timer) a real struct rather than a slintsys alias, so the public API doesn't leak Layer 1 into the v1 contract. This requires wrapping/unwrapping at every Value boundary (Set, Get, callback args, model rows, nested structs), so it's a v1.0 task — see "Toward v1.0" in CLAUDE.md — not a 0.x patch.
func NewImage ¶ added in v0.4.0
NewImage builds an image from any Go image.Image — decoded (image/png, image/jpeg), drawn (image/draw, plotting libs), or generated. Use this to display dynamic content the way Slint's SharedPixelBuffer does in Rust. The pixels are copied, so the source can be reused or freed afterward.
It converts to non-premultiplied RGBA (Slint's expected format); note Go's image.RGBA is *premultiplied*, which this handles correctly.
func NewImageFromData ¶ added in v0.14.0
NewImageFromData builds a raster image from in-memory encoded bytes (PNG/JPEG/…), decoded by Slint. format is an optional lowercase hint ("png", "jpeg", …); "" lets Slint auto-detect. For a Go image.Image (decoded, drawn, or generated), use NewImage instead.
func NewImageFromSVG ¶ added in v0.14.0
NewImageFromSVG builds an image from in-memory SVG bytes (e.g. a go:embed'd .svg). Slint rasterizes the SVG at render size, so it stays crisp at any scale and needs no file on disk — ideal for self-contained binaries and APKs, where @image-url can't resolve a path. Assign it to an `image` property; Close it when done.
func NewImageRGB ¶ added in v0.4.0
NewImageRGB builds an image from a tightly-packed RGB8 buffer (w*h*3 bytes).
type Instance ¶
type Instance struct {
// contains filtered or unexported fields
}
Instance is a live component instance.
func (*Instance) InvokeGlobal ¶
InvokeGlobal calls a callback or function on an exported global.
func (*Instance) OnCallback ¶
OnCallback installs a handler for the named callback.
func (*Instance) OnCloseRequested ¶ added in v0.4.0
OnCloseRequested registers a handler invoked when the window's close is requested (the user clicking the close button, or RequestClose). Return true to allow the window to close, false to keep it open — e.g. to show a confirm dialog or save first. Runs on the event loop.
func (*Instance) OnGlobalCallback ¶
OnGlobalCallback installs a handler for a callback on an exported global.
func (*Instance) RegisterFontFromMemory ¶ added in v0.4.0
RegisterFontFromMemory registers a font from bytes (e.g. a go:embed'd .ttf). The data is copied and kept for the process. (You can also just `import "font.ttf"` in your .slint, which the interpreter registers for you.)
func (*Instance) RegisterFontFromPath ¶ added in v0.4.0
RegisterFontFromPath registers a TrueType/OpenType font file so `.slint` `font-family` can use it. It applies to all windows (registered into the shared context); call it before the text using the font is shown.
func (*Instance) RequestClose ¶ added in v0.4.0
func (i *Instance) RequestClose()
RequestClose asks the window to close, running the OnCloseRequested handler — as if the user clicked the close button.
func (*Instance) RequestRedraw ¶ added in v0.2.0
func (i *Instance) RequestRedraw()
RequestRedraw asks the window to repaint on the next frame.
func (*Instance) Run ¶
Run shows the window and runs the event loop, blocking until the window closes.
func (*Instance) ScaleFactor ¶ added in v0.2.0
ScaleFactor returns the window's device-pixel ratio (physical ÷ logical pixels).
func (*Instance) SetFullscreen ¶ added in v0.2.0
SetFullscreen toggles fullscreen for the window.
func (*Instance) SetMaximized ¶ added in v0.2.0
SetMaximized toggles the maximized state of the window.
func (*Instance) SetMinimized ¶ added in v0.2.0
SetMinimized toggles the minimized (iconified) state of the window.
func (*Instance) SetWindowPosition ¶ added in v0.2.0
SetWindowPosition moves the window (physical pixels). No-op on Wayland; see Instance.WindowPosition.
func (*Instance) SetWindowSize ¶ added in v0.2.0
SetWindowSize sets the window's size in physical pixels.
func (*Instance) Snapshot ¶ added in v0.4.0
Snapshot renders the window's current contents to an image.NRGBA — handy for screenshots, export (encode it with image/png), or visual tests. It may re-render and can be slow; the window should be created (and usually shown) first.
func (*Instance) SnapshotRGBA ¶ added in v0.4.0
SnapshotRGBA is like Snapshot but returns the raw straight-RGBA8 bytes (w*h*4) without allocating an image, for callers that handle pixels directly.
func (*Instance) WindowPosition ¶ added in v0.2.0
WindowPosition returns the window's top-left in physical pixels. It is a no-op on Wayland (the compositor controls placement); it works on X11, Windows, and macOS.
func (*Instance) WindowSize ¶ added in v0.2.0
WindowSize returns the window's size in physical pixels (divide by Instance.ScaleFactor for logical .slint pixels). Most reliable once the window is shown.
type LiveModel ¶ added in v0.15.0
type LiveModel interface{ Handle() *ModelHandle }
LiveModel is a model bindable to a `[T]` property so its rows update in place — a *SliceModel, or the *ModelHandle returned by NewModel. The generated typed Set<Name>Model setters (emitted only for array properties) accept it; unlike the snapshot Set<Name>([]T), the binding stays live (Append/SetRowData/RemoveAt flow to the UI per row).
type ModelHandle ¶
type ModelHandle = slintsys.ModelHandle
ModelHandle binds a Model for use as a property value; report data changes via its Notify* methods. Obtain one with NewModel or SliceModel.Handle.
func NewModel ¶
func NewModel(m Model) *ModelHandle
NewModel binds a custom Model implementation so it can be assigned to a property.
type Option ¶
Option configures a compilation.
func WithFileLoader ¶ added in v0.3.0
func WithFileLoader(fn FileLoader) Option
WithFileLoader installs a fallback resolver for `.slint` imports, letting a multi-file component compile entirely from in-memory source (no files on disk). Generated typed code uses this to embed every imported file.
func WithIncludePaths ¶
WithIncludePaths sets the paths used to resolve `.slint` imports.
func WithLibraryPaths ¶ added in v0.2.0
WithLibraryPaths maps `@library` import names to their paths, e.g. WithLibraryPaths(map[string]string{"mylib": "./libs/mylib"}) resolves `import { Foo } from "@mylib/foo.slint"`.
type SliceModel ¶
type SliceModel struct {
// contains filtered or unexported fields
}
SliceModel is a built-in slice-backed Model whose mutators auto-notify Slint.
func NewSliceModel ¶
func NewSliceModel(items ...any) *SliceModel
NewSliceModel creates a slice-backed model from the given items.
func (*SliceModel) Append ¶
func (s *SliceModel) Append(v any)
Append adds an item and notifies Slint.
func (*SliceModel) Handle ¶
func (s *SliceModel) Handle() *ModelHandle
Handle returns the binding handle (also accepted directly by property setters).
func (*SliceModel) RemoveAt ¶
func (s *SliceModel) RemoveAt(row int)
RemoveAt removes the item at row and notifies Slint.
func (*SliceModel) RowCount ¶
func (s *SliceModel) RowCount() int
RowCount returns the number of rows. Part of the Model interface.
func (*SliceModel) RowData ¶
func (s *SliceModel) RowData(row int) any
RowData returns the value at row, or nil if out of range. Part of the Model interface.
func (*SliceModel) SetRowData ¶
func (s *SliceModel) SetRowData(row int, v any)
SetRowData replaces the value at row (when in range) and notifies Slint. Must be called on the UI thread. Part of the Model interface.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
goslint
command
Command goslint provisions the native Slint shim library for the go-slint bindings and wraps `go build`/`go run` with the right linker configuration.
|
Command goslint provisions the native Slint shim library for the go-slint bindings and wraps `go build`/`go run` with the right linker configuration. |
|
goslint-gen
command
Command goslint-gen generates a typed Go API from a .slint file.
|
Command goslint-gen generates a typed Go API from a .slint file. |
|
examples
|
|
|
chartstress
command
Shared throughput-harness logic for desktop (main.go) and Android (android_main.go).
|
Shared throughput-harness logic for desktop (main.go) and Android (android_main.go). |
|
clock
command
Command clock is an interactive go-slint example using the TYPED API: a repeating Timer driven from Go updates the typed `ticks` property once a second.
|
Command clock is an interactive go-slint example using the TYPED API: a repeating Timer driven from Go updates the typed `ticks` property once a second. |
|
counter
command
Command counter is an interactive go-slint example using the TYPED API (generated by `goslint generate` — see the directive).
|
Command counter is an interactive go-slint example using the TYPED API (generated by `goslint generate` — see the directive). |
|
dragdrop
command
Command dragdrop demonstrates Slint 1.17 drag & drop (DragArea/DropArea) with a real payload bridged to Go.
|
Command dragdrop demonstrates Slint 1.17 drag & drop (DragArea/DropArea) with a real payload bridged to Go. |
|
gradient
command
Command gradient demonstrates building gradient brushes in Go (slint.Gradient) and assigning them to a `brush` property: linear at various angles, radial, a multi-stop rainbow, and an animated rotating gradient driven by a timer.
|
Command gradient demonstrates building gradient brushes in Go (slint.Gradient) and assigning them to a `brush` property: linear at various angles, radial, a multi-stop rainbow, and an animated rotating gradient driven by a timer. |
|
helloworld
command
|
|
|
image
command
Command image generates an image in Go and displays it in the UI via slint.NewImage (the SharedPixelBuffer path) — no image file on disk.
|
Command image generates an image in Go and displays it in the UI via slint.NewImage (the SharedPixelBuffer path) — no image file on disk. |
|
interop
command
Shared Go ⇄ Slint interop logic, used by both the desktop entry (main.go) and the Android entry (android_main.go).
|
Shared Go ⇄ Slint interop logic, used by both the desktop entry (main.go) and the Android entry (android_main.go). |
|
multifile
command
Command multifile is a TYPED example whose .slint imports another .slint (components/card.slint).
|
Command multifile is a TYPED example whose .slint imports another .slint (components/card.slint). |
|
multiwindow
command
Command multiwindow shows several top-level windows from one app.
|
Command multiwindow shows several top-level windows from one app. |
|
systray
command
Command systray demonstrates Slint 1.17's SystemTrayIcon: the app puts an icon in the system tray with a menu (Show/Hide, Quit).
|
Command systray demonstrates Slint 1.17's SystemTrayIcon: the app puts an icon in the system tray with a menu (Show/Hide, Quit). |
|
threadcheck
command
Command threadcheck demonstrates Slint's thread-affinity rule and the goslint dev guard for it.
|
Command threadcheck demonstrates Slint's thread-affinity rule and the goslint dev guard for it. |
|
todo
command
Command todo is an interactive go-slint example showing a live model: a Go SliceModel backs the list, and add/delete are handled in Go.
|
Command todo is an interactive go-slint example showing a live model: a Go SliceModel backs the list, and add/delete are handled in Go. |
|
typed
command
Command typed is the hello example using the TYPED API generated by `goslint generate` (see the //go:generate directive).
|
Command typed is the hello example using the TYPED API generated by `goslint generate` (see the //go:generate directive). |
|
window
command
Command window demonstrates Go-side window control: resizing, positioning, maximize/fullscreen, reading back size/position/scale-factor, and close handling (OnCloseRequested / RequestClose — confirm before exit).
|
Command window demonstrates Go-side window control: resizing, positioning, maximize/fullscreen, reading back size/position/scale-factor, and close handling (OnCloseRequested / RequestClose — confirm before exit). |
|
Package slintsys is the low-level cgo binding to the goslint-sys C ABI (Layer 1).
|
Package slintsys is the low-level cgo binding to the goslint-sys C ABI (Layer 1). |