InstLedRed — LightGUI Python widget

InstLedRed — LightGUI Python widget

InstLedRed is a Instrumentation widget (Instrument archetype) in the Instrumentation category of the LightGUI Python widget set. It is an instrumentation control (gauge, meter, lamp, switch or readout): it shows a live value or state.

Screenshot

InstLedRed example running

The screenshot above is the example program running under Xvfb.

What it does

It is an instrumentation control (gauge, meter, lamp, switch or readout): it shows a live value or state.

Properties

51 properties (8 custom to this widget, the rest are the generic set every widget has). Set a property in code with widget.set_prop(name, value); model-only properties have no live setter.

PropertyTypeDefaultInspectorSetter
nameStr—Nameset_prop("name", value)
leftInt0Leftset_prop("left", value)
topInt0Topset_prop("top", value)
widthInt100Widthset_prop("width", value)
heightInt30Heightset_prop("height", value)
backgroundColor—Colorset_prop("background", value)
foregroundColor—Font.Colorset_prop("foreground", value)
border-widthInt0Border.Widthset_prop("border-width", value)
border-colorColor—Border.Colorset_prop("border-color", value)
border-radiusInt0Border.Radiusset_prop("border-radius", value)
tooltip-textStr—Tooltipmodel-only — no setter; stored on the widget, emitted as a comment by the generator
enabledBooltrueEnabledset_prop("enabled", value)
visibleBooltrueVisibleset_prop("visible", value)
font-nameStr—Font.Nameset_prop("font-name", value)
font-sizeInt13Font.Sizeset_prop("font-size", value)
font-boldBoolfalseFont.Style.Boldset_prop("font-bold", value)
font-italicBoolfalseFont.Style.Italicset_prop("font-italic", value)
font-underlineBoolfalseFont.Style.Underlinemodel-only — no setter; stored on the widget, emitted as a comment by the generator
font-strikeoutBoolfalseFont.Style.StrikeOutmodel-only — no setter; stored on the widget, emitted as a comment by the generator
hintStr—Hintmodel-only — no setter; stored on the widget, emitted as a comment by the generator
show-hintBoolfalseShowHintmodel-only — no setter; stored on the widget, emitted as a comment by the generator
cursorStr—Cursormodel-only — no setter; stored on the widget, emitted as a comment by the generator
tab-orderInt0TabOrdermodel-only — no setter; stored on the widget, emitted as a comment by the generator
tab-stopBooltrueTabStopmodel-only — no setter; stored on the widget, emitted as a comment by the generator
min-widthInt0Constraints.MinWidthset_prop("min-width", value)
min-heightInt0Constraints.MinHeightset_prop("min-height", value)
max-widthInt0Constraints.MaxWidthset_prop("max-width", value)
max-heightInt0Constraints.MaxHeightset_prop("max-height", value)
margin-leftInt0BorderSpacing.Leftmodel-only — no setter; stored on the widget, emitted as a comment by the generator
margin-topInt0BorderSpacing.Topmodel-only — no setter; stored on the widget, emitted as a comment by the generator
margin-rightInt0BorderSpacing.Rightmodel-only — no setter; stored on the widget, emitted as a comment by the generator
margin-bottomInt0BorderSpacing.Bottommodel-only — no setter; stored on the widget, emitted as a comment by the generator
margin-aroundInt0BorderSpacing.Aroundmodel-only — no setter; stored on the widget, emitted as a comment by the generator
autosizeBoolfalseAutoSizemodel-only — no setter; stored on the widget, emitted as a comment by the generator
tagInt0Tagmodel-only — no setter; stored on the widget, emitted as a comment by the generator
anchor-topBooltrueAnchors.Topmodel-only — no setter; stored on the widget, emitted as a comment by the generator
anchor-leftBooltrueAnchors.Leftmodel-only — no setter; stored on the widget, emitted as a comment by the generator
anchor-rightBoolfalseAnchors.Rightmodel-only — no setter; stored on the widget, emitted as a comment by the generator
anchor-bottomBoolfalseAnchors.Bottommodel-only — no setter; stored on the widget, emitted as a comment by the generator
alignEnum (None, Top, Bottom, Left, Right, Client)0Alignmodel-only — no setter; stored on the widget, emitted as a comment by the generator
inner-borderInt0BorderSpacing.InnerBordermodel-only — no setter; stored on the widget, emitted as a comment by the generator
cell-align-horizontalEnum (Left, Center, Right)0BorderSpacing.CellAlignHorizontalmodel-only — no setter; stored on the widget, emitted as a comment by the generator
cell-align-verticalEnum (Top, Center, Bottom)0BorderSpacing.CellAlignVerticalmodel-only — no setter; stored on the widget, emitted as a comment by the generator
textStr—Textset_prop("text", value)
dark-colorColorrgb(40,40,40)DarkColorset_prop("dark-color", value)
hover-colorColorrgb(0,120,200)HoverColorset_prop("hover-color", value)
lead-colorColorrgb(120,120,120)LeadColorset_prop("lead-color", value)
lens-colorColorrgb(220,30,30)LensColorset_prop("lens-color", value)
white-colorColorrgb(255,255,255)WhiteColorset_prop("white-color", value)
brightnessInt100Brightnessset_prop("brightness", value)
onBoolfalseOnset_prop("on", value)

Events

The generated app dispatches mouse events at run time: a button press is hit-tested to the topmost widget under the pointer and fires OnClick (and OnMouseDown); the release goes to the widget that got the press, even if the pointer moved off it, and fires OnMouseUp; a double-click fires OnDblClick. A disabled widget receives no events. Other Lazarus events get a handler stub in the generated code, marked with a NOTE comment, and are kept for hand-wiring.

Events this widget uses:

  • OnClick — dispatched at run time by the generated app
  • OnChange — stub emitted in the generated code; no run-time wiring, kept for hand-wiring
  • OnMouseDown — dispatched at run time by the generated app
  • OnMouseUp — dispatched at run time by the generated app

The example below wires OnClick to on_InstLedRed_001_OnClick, which prints EVENT InstLedRed_001 OnClick when you click the widget.

Font and labels

Change the font in code with the font-name, font-size, font-bold and font-italic props — for example widget.set_prop("font-size", "16") and widget.set_prop("font-bold", "true"). Change the caption with the text prop (widget.set_prop("text", "Hello"), or widget.set_text("Hello")).

Styling

Colours and borders are plain props: background is the fill, foreground is the font/text colour, border-width the border thickness in pixels, border-color its colour, and border-radius rounds the corners (0 = square). For example widget.set_prop("background", "#336699"), widget.set_prop("border-width", "2") and widget.set_prop("border-radius", "8").

Working example

A minimal complete Python program: one window, one InstLedRed, with OnClick wired. It is the LightGUI designer's own codegen output for a project holding just this widget. Run it with the LightGUI Python package on PYTHONPATH:

PYTHONPATH=/opt/lightgui_python python3 instledred.py

Runnable copy in the repo: examples/instledred.py

#!/usr/bin/env python3
# Generated by LightGUI (Python/XFrame).
# A plain Python/GTK program: no CMake. Run with:
#   python3 instledred.py
# with the LightGUI Python package on PYTHONPATH
# (the designer sets it when it runs this script).
#
# The window is 'InstLedRed example' (232x122) with 1 widget(s).

import sys

import gi

gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")

from gi.repository import Gdk, Gtk  # noqa: E402
from lightgui.xframe.core import create, parse_color  # noqa: E402


def on_InstLedRed_001_OnClick(widget):
    print("EVENT %s %s" % (widget.name, 'OnClick'))

# Event handlers, wired to the widgets in main():
_HANDLERS = {
    ('InstLedRed_001', 'OnClick'): on_InstLedRed_001_OnClick,
}


# Design-time geometry + effective anchors per widget:
# name -> (top, left, right, bottom, x, y, width, height)
_ANCHORS = {
    'InstLedRed_001': (True, True, False, False, 16, 16, 200, 90),
}


def _apply_anchors(widgets, width, height):
    """Reposition anchored widgets for a drawing area of
    *width* x *height* (Flag 1: minimal anchor layout).
    Computed from the design geometry every time, so a
    resize is idempotent — no drift across resizes."""
    design_w, design_h = _DESIGN_SIZE
    dx = width - design_w
    dy = height - design_h
    for widget in widgets:
        top, left, right, bottom, ox, oy, ow, oh = \
            _ANCHORS[widget.name]
        x, y, w, h = ox, oy, ow, oh
        if right and not left:
            x = ox + dx
        elif right and left:
            w = ow + dx
        if bottom and not top:
            y = oy + dy
        elif bottom and top:
            h = oh + dy
        widget.move_to(x, y)
        widget.resize_to(w, h)

def _build_widgets():
    """Create every placed widget with its props."""
    widgets = []
    widget = create('InstLedRed', 'InstLedRed_001', 16, 16, 200, 90)
    widget.set_prop('text', 'InstLedRed_001')
    widgets.append(widget)
    return widgets


_DESIGN_SIZE = (232, 122)
_BACKGROUND = ''
_WIDGETS = []
_LAST_SIZE = [None]
_PRESSED = [None]  # Task 4: widget that got the ButtonPress


def _hit_widget(widgets, x, y):
    """Topmost visible widget containing (*x*, *y*)."""
    for widget in reversed(widgets):
        if widget.get_prop("visible", "true") in ("false", "0"):
            continue
        if widget.contains(x, y):
            return widget
    return None


def _dispatch_to(widget, event):
    """Call the *event* handler of *widget* (already chosen)."""
    if widget is None:
        return
    if widget.get_prop("enabled", "true") in ("false", "0"):
        return
    handler = _HANDLERS.get((widget.name, event))
    if handler is not None:
        handler(widget)


def _dispatch(widgets, x, y, event):
    """Call the *event* handler of the widget at (*x*, *y*),
    if it has one wired."""
    _dispatch_to(_hit_widget(widgets, x, y), event)


def _on_draw(area, cr):
    bg = parse_color(_BACKGROUND, None)
    if bg is None:
        bg = (1.0, 1.0, 1.0)
    cr.set_source_rgb(*bg)
    cr.paint()
    for widget in _WIDGETS:
        widget.draw(cr)
    return False


def _on_button_press(area, event):
    if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS:
        _dispatch(_WIDGETS, event.x, event.y, "OnDblClick")
    elif event.type == Gdk.EventType.BUTTON_PRESS:
        _dispatch(_WIDGETS, event.x, event.y, "OnMouseDown")
        _dispatch(_WIDGETS, event.x, event.y, "OnClick")
        # Task 4: remember the pressed widget; release goes there.
        _PRESSED[0] = _hit_widget(_WIDGETS, event.x, event.y)
    return False


def _on_button_release(area, event):
    # Task 4: release goes to the widget that got the press,
    # even if the pointer moved off it.
    widget = _PRESSED[0]
    _PRESSED[0] = None
    _dispatch_to(widget, "OnMouseUp")
    return False


def _on_area_resize(area, allocation):
    size = (allocation.width, allocation.height)
    if size == _LAST_SIZE[0]:
        return False
    _LAST_SIZE[0] = size
    _apply_anchors(_WIDGETS, size[0], size[1])
    area.queue_draw()
    return False


def main():
    window = Gtk.Window(title='InstLedRed example')
    window.set_default_size(232, 122)
    window.connect("destroy", Gtk.main_quit)
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
                    spacing=0)
    window.add(vbox)
    area = Gtk.DrawingArea()
    area.set_hexpand(True)
    area.set_vexpand(True)
    area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK |
                    Gdk.EventMask.BUTTON_RELEASE_MASK)
    area.connect("draw", _on_draw)
    area.connect("button-press-event", _on_button_press)
    area.connect("button-release-event", _on_button_release)
    area.connect("size-allocate", _on_area_resize)
    vbox.pack_start(area, True, True, 0)
    _WIDGETS.extend(_build_widgets())
    window.show_all()
    Gtk.main()
    return 0


if __name__ == "__main__":
    sys.exit(main())