Binding a function to a Widget Button

Hi everyone, I am trying to get a function called when I click on a button In a HUD I made. The code I have is the following:

void ACambiarColorPorCaraCharacter::BeginPlay()
{
// Call the base class
Super::BeginPlay();

if (WidgetInstance) // Check if the Asset is assigned in the blueprint.
{
// Create the widget and store it.
MyController = UGameplayStatics::GetPlayerController(GetWorld(), 0);
APlayerController* PlayerController = Cast<APlayerController>(MyController);
MyWidgetInstance = CreateWidget<UUserWidget>(PlayerController, WidgetInstance);

    if (Cast&lt;UButton&gt;(MyWidgetInstance-&gt;GetWidgetFromName(TEXT("Btn"))) != nullptr)
    {

        UButton* btn= Cast&lt;UButton&gt;(MyWidgetInstance-&gt;GetWidgetFromName(TEXT("Btn")));

        btn-&gt;OnClicked.AddDynamic(this, &ACambiarColorPorCaraCharacter::btn_pressed);
   }

}

}

btn_pressed is a simple UE_Log. I cannot get this to work, any ideas why? Also, i know the btn varaible is created and WidgetInstance has a reference to the HUD widget I made because I used EU_Log to check, just removed those for clarity here. Thanks in advance.

I bind them from the Blueprint to the CPP class of the menu like this:

First Make Sure Your Button is named in your CPP exactly as it is in your widget blueprint
Second Make Sure your Blueprint is in fact parented to your CPP class

Put this in the Header:



public:

    UPROPERTY(meta = (BindWidget))
    class UButton* YourButton;

    void YourButtonClicked();


protected:

    virtual bool Initialize();



Put this in the CPP file:




#include "Components/Button.h"

bool UYourClassName::Initialize()
{
    bool success = Super::Initialize();
    if (!success)  return false;

    if (!ensure(YourButton != nullptr)) return false;
    YourButton->OnClicked.AddDynamic(this, &UYourClassName::YourButtonClicked);
}

void UYourClassName::YourButtonClicked()
{

// Whatever you want to do goes here

}



Recompile both the Project and the Widget BluePrint

NOTE: This is not the way to bind it to a character class as you are doing but to a custom CPP class descending from UUserWidget that can talk to your character class.

2 Likes

The code from Colorado gave me an error C4715 as there was no return value if it passed. For me the answer in below post from **Ninja_K**worked.

Can we have parameters in the ‘YourButtonClicked’ ?
Thanks