DEV Community

泽
泽

Posted on

Zekit widget base classes: ownership, geometry, and repaint rules in C++

Zekit is a C++20 desktop GUI toolkit that compiles to a single static library. This post covers the layer under every widget: the base classes, and the one rule that explains most of their API.

The library has four base classes. They stack:

Base class Responsibility
Widget geometry, hit testing, focus, value semantics
BoxWidget box appearance: body, border, radius, shadow
TextWidget single-line text layout and four text states
Panel everything above, plus layout — the one to inherit for custom containers

Widget doesn't know what a widget looks like. BoxWidget doesn't handle text. TextWidget doesn't lay out children. Pick the shallowest base that does what you need.

The rule behind most of this: widgets are values

Kit::Label tip("Hello");
win.AddWidget(tip);
Enter fullscreen mode Exit fullscreen mode

AddWidget takes a widget by value. It moves the value into the window's tree and takes ownership. The tree is destroyed with the window, so:

  • no new, no delete, no unique_ptr;
  • no member variable kept around just to keep a widget alive;
  • no destruction-order questions;
  • no null pointers to check.

The consequence you must internalise: your local tip is a moved-from shell afterwards. Anything you want to do to the widget goes through the returned reference:

Kit::Label& tip = win.AddWidget(Kit::Label("Hello"));
tip.SetGeometry(24, 16, 120, 60);
Enter fullscreen mode Exit fullscreen mode

That's why examples write auto& and not auto. If you need to prove it to yourself:

Kit::Label source("I will be moved");
Kit::Widget* oldPtr = &source;

Kit::Label& placed = win.AddWidget(source);

oldPtr->isMovedFrom();    // true  — the shell
placed.isMovedFrom();     // false — the real widget
Enter fullscreen mode Exit fullscreen mode

Corollary: don't hold widget pointers across an ownership change. The address moves. Use names instead (see below).

Four tree operations: attach, detach, destroy, move

Operation Call Semantics
attach AddWidget / AddChild takes the value, moves it in
attach (raw) AddWidgetUnchecked skips the layout check, for custom classes
detach RemoveWidget leaves the tree, not destroyed
destroy DestroyWidget destructs the subtree, frees the storage
clear ClearChildren removes all direct children
move out releaseChild returns a unique_ptr, storage included
move in adoptChild takes a unique_ptr and its ownership

The distinction worth memorising:

Detach so you can use it again. Destroy because you're done with it.

RemoveWidget only unlinks the node. The object stays alive — members, subtree, geometry — it just stops being drawn, hit-tested and laid out. DestroyWidget is the real thing, and you must re-run layout afterwards:

list.DestroyWidget(*list.children().front());
list.Invalidate();    // without this, layout still counts the old node
Enter fullscreen mode Exit fullscreen mode

releaseChild / adoptChild are the pair you use when a widget moves between containers — dragging a tab out into its own window, for instance.

Two compile-time details:

AddWidgetUnchecked exists for one situation: a class deriving from Widget that attaches children in its own constructor. Widget doesn't lay out children, so AddWidget on it is marked deprecated and gives you C4996. The unchecked variant says "I know it doesn't lay out, I'll handle it".

Paint is pure virtual on Widget, so a direct subclass must implement it, even empty. Skip it and you get C2259 (cannot instantiate abstract class).

Honestly: if you're writing a container, inherit Panel. It lays out children and you get AddChild for free. AddWidgetUnchecked is for people who genuinely do their own layout.

Geometry: write, read, measure

Call Writes
SetSize(w, h) size intent only — the parent decides position
SetGeometry(x, y, w, h) position and size at once
SetPosition / SetX / SetY position only

Reading gives you actual geometry, after layout:

btn.x(); btn.y(); btn.width(); btn.height();
Enter fullscreen mode Exit fullscreen mode

Three different size numbers exist on every widget, and mixing them up causes most layout bugs:

Read Meaning
prefWidth() what you asked for (0 if you never said)
hintWidth() what the content needs
width() what layout actually gave

pref is intent, hint is content, width is fact. Only width() is "how big it is right now"; the other two are inputs to layout.

After changing text, size does not update by itself — the text just gets clipped:

btn.SetText("A much longer label");
btn.AutoSize();     // re-measure from content
Enter fullscreen mode Exit fullscreen mode

SetDefaultSize is the fallback used when neither of the other two applies. It doesn't touch pref, so your intent survives.

Size policy: rules, not numbers

These calls almost never set a size. They describe a relationship with the parent layout, which then computes the geometry.

Call Rule
SetSizePolicy does this widget want the leftover space on this axis
SetMinSize / SetMaxSize how small / how large may it get
SetMargin distance to neighbours (outside the widget, so its own size doesn't shrink)
SetFlexGrow share of leftover space, by weight
SetAlignSelf alignment on the cross axis, for this widget only
SetFillWindow fill the client area and follow resizes
Kit::VBoxLayout& box = win.AddWidget(Kit::VBoxLayout());
box.AddChild(Kit::Label("A title that takes one row"));

Kit::Panel& body = box.AddChild(Kit::Panel());
body.SetSizePolicy(Kit::SizePolicy::Preferred,
                   Kit::SizePolicy::Expanding);   // vertical: eat the rest
Enter fullscreen mode Exit fullscreen mode

Not a single pixel value in that snippet, and the layout is fully determined.

Weights are proportional, not absolute:

b.SetFlexGrow(1.0f);   // one share
c.SetFlexGrow(2.0f);   // two shares — leftover width splits 1 : 2
Enter fullscreen mode Exit fullscreen mode

And constraints clamp requests, they don't override them silently:

box.SetMinSize(200.0f, 80.0f);
box.SetMaxSize(360.0f, 160.0f);
box.SetSize(100.0f, 50.0f);   // becomes 200 × 80
Enter fullscreen mode Exit fullscreen mode

Painting and repaint discipline

Everything here follows from segment caching: the window does not repaint every widget every frame. A widget's vertices are cached, and an unchanged widget reuses last frame's geometry.

The good news is performance. The price is a rule:

If you change appearance, mark the widget dirty. The cache will happily show you the old picture otherwise.

Call Purpose
Paint(FrameCollector&) the only place a widget describes itself
clipChildrenRect() where children get clipped
paintsOnTop() draw after everything else
wantsAnimationFrame() keep the window awake for animation
RequestWindowRedraw() mark dirty and schedule a frame
InvalidatePaint() mark dirty only, no scheduling
SetVisible(false) not drawn, still in the tree
SetEnabled(false) still drawn and still occupying space, but not interactive
void SetState(int v) {
    state_ = v;
    RequestWindowRedraw();   // without this, nothing changes on screen
}
Enter fullscreen mode Exit fullscreen mode

For batch updates, one scheduled frame is enough:

for (Kit::Label* l : labels) {
    l->SetText(std::to_string(n));
    l->InvalidatePaint();      // dirty only
}
batch.RequestWindowRedraw();   // schedule once
Enter fullscreen mode Exit fullscreen mode

Events: one return-value convention

Hit testing first — the default is a rectangle, which is wrong as soon as you draw a circle:

bool HitTest(float x, float y) const override {
    const float cx = this->x() + width() * 0.5f;
    const float cy = this->y() + height() * 0.5f;
    return std::hypot(x - cx, y - cy) <= width() * 0.5f;
}
Enter fullscreen mode Exit fullscreen mode

Then events, all as virtual On... methods, all with the same convention: return true to consume, false to let the parent handle it.

Group Entry points
Mouse OnMousePress / OnMouseRelease / OnMouseMove / OnMouseWheel
Enter/leave OnMouseEnter / OnMouseLeave
Touch OnTouchBegin / OnTouchUpdate / OnTouchEnd / OnTouchCancel
Keyboard OnKeyPress (semantic key) / OnCharInput (actual character)

Keep the last row straight: OnKeyPress is the key, OnCharInput is the character. Single-finger taps arrive as mouse events already; the touch group is for multi-touch.

To intercept before a subtree sees anything, install a filter:

class BlockA : public Kit::EventFilter {
public:
    bool onKey(Kit::Window&, Kit::KeyEvent& e) override {
        return e.key == Kit::Key::A;   // true → swallowed
    }
};

BlockA blocker;                                  // must outlive the install
const auto id = pad.InstallEventFilter(blocker);
Enter fullscreen mode Exit fullscreen mode

Focus: three questions, three calls

Focus is a single global state arbitrated by the window. Widgets only get notified. The three questions people collapse into one:

Question Call
Am I eligible to be focused? isFocusable()
Is it my turn? (enabled, not covered) isFocusTarget()
Am I holding it right now? hasFocus()
edit.SetEnabled(false);
edit.isFocusTarget();   // false — Tab and clicks skip it
Enter fullscreen mode Exit fullscreen mode

Eligibility is opt-in: SetFocusable(true), default false.

OnFocusIn / OnFocusOut are virtual with no callback registration, and you must call the base implementation — an input widget uses it to reset the caret and finish or cancel IME composition. Skipping it produces "the caret doesn't blink" and "the candidate window won't disappear" bugs.

Finding widgets: names survive moves

Since pointers die when widgets move, give them a name:

title.SetObjectName("title");

if (auto* p = panel.FindWidget<Kit::Label>("title"))
    p->SetText("Found it");
Enter fullscreen mode Exit fullscreen mode
Call Scope
FindWidget<T>(name) direct children only
FindWidgetDeep<T>(name) recursive, returns the first match
FindAll<T>(name) all matches as a vector
VisitTree(fn) pre-order walk with (widget, depth)
SetWidget(name, w) insert or replace in place

FindWidget requires both name and type to match; either mismatched and you get nullptr:

win.FindWidget<Kit::Label>("row");    // not recursive → nullptr
win.FindWidget<Kit::Button>("target");// right name, wrong type → nullptr
Enter fullscreen mode Exit fullscreen mode

SetWidget is the correct way to update content in place:

col.SetWidget("mid", Kit::Label("first pass"));    // creates
col.SetWidget("mid", Kit::Label("second pass"));   // replaces, doesn't stack
Enter fullscreen mode Exit fullscreen mode

Delete-then-add accumulates widgets on any missed removal; SetWidget uses the name as a slot.

BoxWidget: one box, several independent slots

Appearance lives here, and the mental model is slots: body, border, radius, content, plus background image, shadow and outline. They're independent, which is why "same background, five border styles" is a one-line change.

Kit::Button b;
b.SetBodyColor(Kit::Color4f::FromHex(0xE5484D));
b.SetHoverBodyColor(Kit::Color4f::FromHex(0xE5484D));  // or it jumps to the theme colour
b.SetBorderWidth(0.0f);                                // theme default would show through
Enter fullscreen mode Exit fullscreen mode

Colours come in five shapes, all the same type:

Form Use
Color4f::FromHex(0x0091FF) the usual one
Color4f::White() named colours
Color4f{0, 0, 0, 0.5f} r, g, b, alpha
c.withAlpha(0.6f) alpha only
c.lighten(0.25f) toward white — this is how you derive a hover colour

Prefer semantic radius over pixels: SetRadiusMode(Kit::RadiusMode::Capsule) follows the theme, while SetRadius(8) pins a number.

Panel, and why it's the default choice

class Card : public Kit::Panel {
public:
    Card() {
        SetBackground(Kit::Color4f::FromHex(0xFFFFFF));
        AddChild(Kit::Label("A card title"));   // laid out automatically
    }
};
Enter fullscreen mode Exit fullscreen mode

Inheriting Panel gives you layout, background and border. Children added with AddChild queue themselves — the "everything piled in the top-left corner" problem doesn't exist here.

Five things worth remembering

  1. Widgets are values; AddWidget moves them, so use the returned reference.
  2. Detach is not destroy.
  3. Policy writes rules, layout computes pixels — pref, hint and width are three different numbers.
  4. Segment caching means you must mark dirty; batch with "dirty each, schedule once".
  5. Events return true to consume, false to bubble.

Source and docs: https://github.com/Z-ze489/Zekit.

Top comments (0)