Hello,
I know that a lot of people are not big fans of OOP, but I was trying to setup a simple widget hierarchy system using basic inheritance. As of now, this is what I tried to do (or at least a barebones version):
type
Widget = ref object of RootObj
root: Widget
parent: Widget
children: seq[Widget]
enabled: bool = true
WText = ref object of Widget
label: string
WButton = ref object of Widget
label: string
state: bool
on_click: proc()
WCheckbox = ref object of Widget
label: string
state: bool
on_change: proc()
WSeparator = ref object of Widget
label: string = ""
WHbox = ref object of Widget
proc attach[N, M: Widget](parent: var N, child: var M) =
parent.children.add(child)
child.parent = parent
# The root is either the parent if it's of highest rank, or the parent's root
if parent.root.isNil:
child.root = parent
else:
child.root = parent.root
proc `[]`[W: Widget](parent: var W, children: varargs[var W]): W =
for child in children:
parent.attach(child)
return parent
var
layout_root = WHBox()[
WButton(),
WText(),
WHBox()[
WCheckbox(),
WSeparator(),
WCheckbox()
]
]
The point is to be able to define the hierarchy "visually", as shown with the layout_root declaration. However, I can't seem to make it work. I keep on getting errors about immutability, and I can't seem to understand the root of the problem, as every attempt I make at finding a solution brings another problem.
Is there a way to do what I'm trying? Or am I just doing complete nonsense? I have a feeling that this boils down to some memory management concepts that I do not understand, but it's always complicated to detect what you don't understand, when you don't understand it :') I'm also not sure if I'm using generics in a proper way, I might not. Thanks to anyone who replies for their patience, I'm probably being quite dumb right now