Connect a numerical callback property with a Qt widget containing text.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QtWidget
        The Qt widget to connect. This should implement the ``setText`` and
        ``text`` methods as well optionally the ``editingFinished`` signal.
    fmt : str or func
        This should be either a format string (in the ``{}`` notation), or a
        function that takes a number and returns a string.

def connect_float_text(instance, prop, widget, fmt="{:g}"):
    """
    Connect a numerical callback property with a Qt widget containing text.

    Parameters
    ----------
    instance : object
        The class instance that the callback property is attached to
    prop : str
        The name of the callback property
    widget : QtWidget
        The Qt widget to connect. This should implement the ``setText`` and
        ``text`` methods as well optionally the ``editingFinished`` signal.
    fmt : str or func
        This should be either a format string (in the ``{}`` notation), or a
        function that takes a number and returns a string.
    """

    if callable(fmt):
        format_func = fmt
    else:
        def format_func(x):
            return fmt.format(x)

    def update_prop():
        val = widget.text()
        try:
            setattr(instance, prop, float(val))
        except ValueError:
            setattr(instance, prop, 0)

    def update_widget(val):
        if val is None:
            val = 0.
        widget.setText(format_func(val))

    add_callback(instance, prop, update_widget)

    try:
        widget.editingFinished.connect(update_prop)
    except AttributeError:
        pass

    update_widget(getattr(instance, prop))