edifice.Reference

edifice.Reference#

class edifice.Reference[source]#

Bases: object

Reference to a Element to allow imperative modifications.

While Edifice is a declarative library and tries to abstract away the need to issue imperative commands to widgets, this is not always possible, either due to limitations with the underlying backened, or because some feature implemented by the backend is not yet supported by the declarative layer. In these cases, you might need to issue imperative commands to the underlying Widgets and Elements, and Reference gives you a handle to the currently rendered Element.

Create a Reference with the use_ref() Hook:

@component
def MyComp(self):
    ref = use_ref()

    def issue_command(e):
        ref().command()

    AnotherElement(on_click=issue_command).register_ref(ref)

Under the hood, Element.register_ref() registers the Reference object to the Element returned by the render function. While rendering, Edifice will examine all requested references and attaches them to the correct Element.

Initially, a Reference object will point to None. After the first render, it will point to the rendered Element. When the rendered Element dismounts, the reference will once again point to None. You may assume that Reference is valid whenever it is not None. Reference will evaluate false if the underlying value is None.

Reference can be dereferenced by calling it. An idiomatic way of using references is:

if ref:
    ref().do_something()

If you want to access the QWidget underlying a Base Element, you can use the underlying attribute of the Element. use_effect() Hooks always run after the Elements are fully rendered:

@component
def MyComp(self):
    ref = use_ref()

    def did_render():
        element = ref()
        assert isinstance(element, Label)
        element.underlying.setText("After")
        return lambda:None

    use_effect(did_render, ref)

    with View():
        Label("Before").register_ref(ref)

Methods

__init__()