ui_xml.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package qt
  2. import (
  3. "fmt"
  4. "errors"
  5. "unicode"
  6. "reflect"
  7. )
  8. func LoadWidget(ui_xml string, base_dir string, ctx Pkg, k func(Widget)(error)) error {
  9. var w, err = loadWidget(ui_xml, base_dir, ctx)
  10. if err != nil {
  11. return fmt.Errorf("failed to load widget from ui xml: %w", err)
  12. }
  13. return k(w)
  14. }
  15. func (obj Object) FindChild(name string, v reflect.Value) error {
  16. var child, ok = findChild(obj, name)
  17. if !(ok) {
  18. return errors.New(fmt.Sprintf("child Object %s not found", name))
  19. }
  20. var err = child.AssignTo(v)
  21. if err != nil {
  22. return fmt.Errorf("child %s: %w", name, err)
  23. }
  24. return nil
  25. }
  26. func (obj Object) AssignTo(v reflect.Value) error {
  27. if v.Kind() != reflect.Ptr { panic("invalid argument") }
  28. var class = obj.ClassName()
  29. var required = (func() string {
  30. var type_name = v.Elem().Type().Name()
  31. return ("Q" + type_name)
  32. })()
  33. if class == required {
  34. var target = v.Elem().Field(0)
  35. for !(reflect.TypeOf(obj).AssignableTo(target.Type())) {
  36. target = target.Field(0)
  37. }
  38. target.Set(reflect.ValueOf((interface{})(obj)))
  39. return nil
  40. } else {
  41. return errors.New(fmt.Sprintf(
  42. "class not matching: %s (%s)", class, required))
  43. }
  44. }
  45. func (obj Object) AssignChildrenTo(v reflect.Value) error {
  46. if v.Kind() != reflect.Ptr { panic("invalid argument") }
  47. if v.Elem().Kind() != reflect.Struct { panic("invalid argument") }
  48. var struct_v = v.Elem()
  49. var struct_t = struct_v.Type()
  50. for i := 0; i < struct_t.NumField(); i += 1 {
  51. var field_name = struct_t.Field(i).Name
  52. var field_type = struct_t.Field(i).Type
  53. var t = ([] rune)(field_type.Name())
  54. t[0] = unicode.ToLower(t[0])
  55. var field_type_name = string(t)
  56. var child_name = (field_type_name + field_name)
  57. var err = obj.FindChild(child_name, struct_v.Field(i).Addr())
  58. if err != nil { return err }
  59. }
  60. return nil
  61. }