Search code examples
textlabelsignalsgodot

Godot: Label to "actively" fire Signal when (not) empty


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?


Solution

  • 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()