MaxPower
MaxPower

Reputation: 45

How do I access the index from a clicked UI Button inside a widget in Unreal Engine 4 C++?

I am working on a UI menu using Unreal Engine 4 and C++. I have this code (taken from this thread):

H: 
UPROPERTY(meta = (BindWidget)) UButton* TestButton;

UFUNCTION() void OnClick();

CPP:
void UWidgetClassName::NativeConstruct() 
{
    Super::NativeConstruct();

    if (!TestButton->OnClicked.IsBound()) TestButton->OnClicked.AddDynamic(this, &UWidgetClassName::OnClick);
}

void UWidgetClassName::OnClick() 
{
     //I want to access the index of the clicked button here
}

The code is a bit simplified, I actually create this buttons dynamically inside a loop, so I end up with many buttons, all of which call the same function. Is there a way to "know" which button was pressed, so for example if I press the first button, I get 1, if I press the second, I get 2, etc?

Thanks a lot :)

Upvotes: 0

Views: 1689

Answers (2)

Chris Pavs
Chris Pavs

Reputation: 205

I think the only solution, like @rdfoe mentioned, is to create your own Button class. I couldn't find a good example online, so I'll add the one I made here.

Instead of returning the index alone, I made the index a public member of the button and returned a reference to the button itself.


ContextButton.h

#pragma once

#include "CoreMinimal.h"
#include "Components/Button.h"
#include "ContextButton.generated.h"

// Define a new "delegate" type called "FContextClickDelegate" which expects a
// UContextButton* argument named "button".
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FContextClickDelegate, UContextButton*, button);

/**
 * A custom button to add another OnClick delegate.
 */
UCLASS()
class VR_2_API UContextButton : public UButton
{
    GENERATED_BODY()

public:
    UContextButton();

    UPROPERTY(BlueprintAssignable)
    FContextClickDelegate OnClickedWithContext; // This is the event you'll use.

    UPROPERTY(BlueprintReadWrite)
    int index; // Assign this when the button is first created.

private:
    UFUNCTION()
    void ContextOnClicked();
};

ContextButton.cpp

#include "ContextButton.h"

UContextButton::UContextButton()
{
    // Add "UContextButton::ContextOnClicked" to the list of functions that get
    // called when "OnClicked" fires.
    OnClicked.AddDynamic(this, &UContextButton::ContextOnClicked);
}

void UContextButton::ContextOnClicked()
{
    // Fire the "OnClickedWithContext" event and pass a reference to self.
    OnClickedWithContext.Broadcast(this);
}

Upvotes: 0

rdFoe
rdFoe

Reputation: 11

So what you could do is make your own button class which you create dynamically and on click you return some form of identifier like and index or something? If you want to keep it generic you can also add them to some sort of container/list and access the specific button via GetAllChildren on the container which returns an array.

Hope that helps!

Upvotes: 1

Related Questions