F# 🤝 GTK4
Luis Ángel Méndez Gort

Luis Ángel Méndez Gort @lamg

About: Solving problems

Location:
Germany
Joined:
Apr 4, 2023

F# 🤝 GTK4

Publish Date: Oct 17 '24
0 2
#r "nuget: GirCore.Gtk-4.0,0.5.0"

open System
open Gtk

let label () =
  let label = new Label()
  label.SetText "hello"
  label

let button (label: Label) =
  let button = new Button()
  button.SetLabel "click me"
  let mutable counter = 0

  let clickHnd (_: Button) (_: EventArgs) =
    label.SetText $"hello {counter}"
    counter <- counter + 1

  button.add_OnClicked (new GObject.SignalHandler<Button>(clickHnd))
  button

let box () =
  let box = new Box()
  box.SetOrientation Orientation.Vertical
  box.SetHomogeneous true

  let l = label ()
  box.Append l
  button l |> box.Append
  box

let onActivateApp (sender: Gio.Application) (_: EventArgs) =
  let window = ApplicationWindow.New(sender :?> Application)
  window.Title <- "Gtk4 Window"
  window.SetDefaultSize(300, 300)
  window.SetChild(box ())
  window.Show()

let application = Application.New("org.gir.core", Gio.ApplicationFlags.FlagsNone)
application.add_OnActivate (new GObject.SignalHandler<Gio.Application>(onActivateApp))
application.RunWithSynchronizationContext(null)
Enter fullscreen mode Exit fullscreen mode

The above code does the following:

  • creates a 300px × 300px window with GTK4
  • the window title is "Gtk4 Window"
  • it has a button and a label controls
  • when clicking the button the label text changes to show the value of a counter that increases with each click

Notice the code is an F# script, which means it doesn't need a main function and can run by putting the code in an .fsx file and then running it with dotnet fsi your_file.fsx

Comments 2 total

  • Giulliano Ferreira
    Giulliano FerreiraOct 17, 2024

    Is there any advantage of using GTK instead of something like Avalonia?

    • Luis Ángel Méndez Gort
      Luis Ángel Méndez GortOct 18, 2024

      A simple window in GTK seems to be more resource efficient than one in Avalonia. On the other hand Avalonia has functional wrappers that might be more appealing to some people.

Add comment