Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Created March 4, 2021 21:19
Show Gist options
  • Save emad-elsaid/35672e102502bbb3f8df1118e9dd70a8 to your computer and use it in GitHub Desktop.
Save emad-elsaid/35672e102502bbb3f8df1118e9dd70a8 to your computer and use it in GitHub Desktop.
this will load a UI/glade file using GTK builder and will bind objects from the UI to a go struct using the struct field tag as an ID
package main
import (
"fmt"
"log"
"reflect"
"github.com/gotk3/gotk3/gtk"
)
type ApplicationWindow struct {
Name string
ID *gtk.ApplicationWindow `gtk:"window"`
}
func bindUI(filename string, ui interface{}) error {
content, err := gtk.BuilderNewFromFile(filename)
if err != nil {
return fmt.Errorf("Can't read file %w", err)
}
ptr := reflect.ValueOf(ui)
val := ptr.Elem()
st := val.Type()
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
id := field.Tag.Get("gtk")
if id == "" {
continue
}
obj, err := content.GetObject(id)
if err != nil {
return fmt.Errorf("Unable to find object %s for field %s, err: %w", id, field.Name, err)
}
val.Field(i).Set(reflect.ValueOf(obj))
}
return nil
}
func main() {
gtk.Init(nil)
win := ApplicationWindow{}
win.Name = "hello"
err := bindUI("interface/app.glade", &win)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", win.Name)
win.ID.ShowAll()
win.ID.Connect("destroy", func() {
gtk.MainQuit()
})
gtk.Main()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment