Tutorials»Custom Widget

Custom Widget

A simple widget

The simplest kind of widget that may be created will of the form:

class MyWidget : CustomWidget {
    // user code

    mixin (defineProperties("...."));
    mixin MWidget;
}

Where all properties defined in the widget will be taken from outside widgets defined in a config file.

Please note that the defineProperties string mixin and the MWidget template mixin should be located at the very end of the class. This is to ensure their ability to introspect the fields the class defines.

A more complex widget

Any slightly more complex widget will want to set styles and handle inputs. Let's take a look at the GenericButton widget as an example:

class GenericButton : CustomWidget {
    EventHandling handleClick(ClickEvent e) {
        ....
            this._clicked = true;
        ....
    }

    EventHandling handleMouseButton(MouseButtonEvent e) {
        ....
                enableStyle("active");
                _active = true;
        ....
    }

    bool globalHandleMouseButton(MouseButtonEvent e) {
        ....
                disableStyle("active");
                _active = false;
        ....
    }

    EventHandling handleMouseEnter(MouseEnterEvent e) {
        _hover = true;
        enableStyle("hover");
        ....
    }

    EventHandling handleMouseLeave(MouseLeaveEvent e) {
        _hover = false;
        disableStyle("hover");
        ....
    }

    override void onGuiStructureBuilt() {
        this._clicked = false;
        super.onGuiStructureBuilt();
    }

    this() {
        this.addHandler(&this.handleClick);
        this.addHandler(&this.handleMouseButton);
        this.addHandler(&this.handleMouseEnter);
        this.addHandler(&this.handleMouseLeave);
    }

    mixin(defineProperties(
    "inline out bool clicked, inline out bool active, inline out bool hover"));
    mixin MWidget;
}

In this case, the widget defines inline properties and manages their state on its own. For instance when ClickEvent is handled, the clicked property is updated. Similarly, MouseButtonEvent affects the active property and MouseLeaveEvent/MouseEnterEvent determines the state of hover.

In addition to setting property values, the custom widget code enables and disables styles. Where are they defined and how does the widget look at all? That's all up to the config files and any sub-classes of the widget.