-
Notifications
You must be signed in to change notification settings - Fork 34
Reading Glade UI files and binding elements to structs
Emad Elsaid edited this page Mar 5, 2021
·
2 revisions
The following code snippet is useful to demonstrate you can create structs with gtk
tag in front of the fields and this function will get every element by its ID and set it to the struct field.
it also accepts another argument for signals that can bind signals names from glade to a function in go. which can be a struct method.
you can extend the concept to have the struct has a signals
function that returns the signals instead of passing it explicitly to the function.
import (
"fmt"
"reflect"
"github.com/gotk3/gotk3/gtk"
)
func BindUI(filename string, ui interface{}, signals *map[string]interface{}) error {
content, err := gtk.BuilderNewFromFile(filename)
if err != nil {
return fmt.Errorf("Can't read file %w", err)
}
if signals != nil {
content.ConnectSignals(*signals)
}
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
}