c++user-interfaceunreal-engine4unreal-umg

Click function on Toggle Buttons in Unreal Engine 4 C++


I have a doubt about CheckBoxes and click events. I have some button which executes a function OnClick, something like this on code:

SomeButton->OnClicked.AddDynamic(this, &ClassName::FunctionToExecute);

For style reasons, I thought that I should use a Toggle Button, implemented with a CheckBox, instead of a regular Button. However, I am having trouble finding the correct method to bind the function to each click. So far, I tried something like this, but it doesn't work. I also tried declaring a delegate, but it won't work either.

SomeCheckBox->OnCheckStateChanged.Add(&ClassName::FunctionToExecute);

What is the correct way to bind the function to the OnCheckStateChanged() event? Thanks a lot in advance :smile:


Solution

  • If you are using a UMG Check box (which it sounds like you are), than we can look at the delegate declaration:

    // In Checkbox.h 
    DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam( FOnCheckBoxComponentStateChanged, bool, bIsChecked );
    

    and notice that we need a bool input parameter for our callback function.

    So that means that our callback function has to look like this:

    void UYourWidget::OnCheckboxChanged(bool bIsChecked) {}
    

    You can then bind your widget like this:

    if(CheckBox)
    {
        CheckBox->OnCheckStateChanged.AddDynamic(this, &UTextChatWidget::Test);
    }
    

    If you are using a slate check box, then the callback function declaration is a bit different. It uses the ECheckBoxState enum instead of a boolean.

    SNew(SCheckBox)
       .OnCheckStateChanged(this, &SFoo::OnStateChanged)
    
    void SFoo::OnStateChanged(ECheckBoxState NewState) {}
    

    My typical approach for figuring this stuff out is to simply do a CTRL+SHIFT+F search for the delegate in Visual Studio to find other examples of it.