Search code examples
dynamic-programminggdscriptgodot4

in gdscript how do you get the toggled function to do something when a checkbox is clicked in the godot engine


in gdscript (using godot 4.1.1 stable) i am working on a function that adds a checkbox dynamically works fine but when i try to get it to do something when it is toggled i get all sorts of errors this is my small function

func _on_add_left_button_pressed():
    var checkbox = CheckBox.new()
    var text = houseNum.text
    leftList.add_child(checkbox)
    checkbox.text = text
    checkbox.connect("toggled", self, "_on_checkbox_toggled")

currently i have the "_on_checkbox_toggled" defined above but it dosent do anything at the moment just has a print statement in it

the checkbox.connect line gives me an error that says:

Invalid argument for "connect()" function: argument 2 should be "Callable" but is "res://main.gd"

any help would be much appreciated


Solution

  • You seem to be calling the connect method incorrectly.

    In Godot4, the only parameters we need to pass to the method is the signal name and the function to be called when the signal fires.

    So try something like this instead:

    func _on_add_left_button_pressed():
        var checkbox = CheckBox.new()
        checkbox.connect("toggled", _on_checkbox_toggled)
        leftList.add_child(checkbox)
    
    func _on_checkbox_toggled(is_toggled):
        print("Checkbox is toggled: ", is_toggled)
    

    Here is the link to the official docs on connecting to signals via code. The page also shows various other ways of connecting to signals programmatically or through the editor: https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html#connecting-a-signal-via-code