Random beginner-question: Label to "actively" fire Signal when (not) empty

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By pferft

Hi everyone,

how could I have my Label fire a Signal at the moment when there is no text in it (the last remaining character has just been erased and the label is empty) and when a first character is written into the empty label (so it’s not empty anymore)?

Both if text.empty(): and if not text.empty(): work when I “actively” look for the actual state, say, by pressing a connected button, but I can’t figure out how I could make the Label emit such a signal “actively” on its own when changing to said state. How could this be done?

:bust_in_silhouette: Reply From: pferft

Well, kleonc via reddit just slipped me this (thanks a million!):

You can create your own signal in the label’s script. You can override _set method in where you can check if the text property is being changed and do something based on the new value. Something like this should work:

extends Label

signal textChanged(newText)

func _set(property, value):
    match property:
        "text":
            if text != value:
                text = value
                emit_signal("textChanged", value)
                return true
    return false

and then you can just connect some methods to that signal:

    # ...
    yourLabel.connect("textChanged", self, "onLabelTextChanged")
    # ...

func onLabelTextChanged(newText):
    yourEraseButton.disabled = newText.empty()

So the effect here is that it’s emitting a Signal when there is text in the label.

Now I wonder how I could add another signal to be emitted when the label turns empty. I tried playing around with “if not…” but couldn’t succeed. Maybe touching that “value” could lead somewhere? Any ideas?

pferft | 2020-12-03 11:52

And again kleonc to the rescue:

extends Label

signal textChanged(newText)
signal textEmptied

func _set(property, value):
    match property:
        "text":
            if text != value:
                text = value
                emit_signal("textChanged", text)
                if text.empty():
                    emit_signal("textEmptied")
                return true
    return false

pferft | 2020-12-03 12:20