C++ UMG Setting Button OnClicked

From c++, extending from UUserWidget what is the best way to get a reference to your subobjects (buttons, textfields, etc…)?

I was hoping for something along the lines of:

UButton* exitButton = (UButton*)GetWidgetFromName(TEXT("exitButton"));
exitButton->OnClicked.AddDynamic(this, &URoMMainMenuWidget::exitGame);

According to other posts it looks like you have to step through each component:

TSharedRef<SWidget> USubmergedOptionsMenuUserWidget::RebuildWidget()
  {   
      TSharedRef<SWidget> OurWidget = Super::RebuildWidget();
  
      for (UWidget* Widget : Components)
      {
          if (Widget->IsA(USubmergedMenuWidget::StaticClass()))
          {
              //found it now do whatever you need to it, store the pointer etc
              break;
          }
      }
  
      return OurWidget;
  }

But “Components” is not a valid class member so the compile fails. Can someone explain what I am missing?

Anyone? It seems like this basic practice should be documented… All I want to do is find my exit button to add an event to it in C++.

My issue was that I was searching for widgets before they were initialized. Placing my code in the Construct_Implementation() corrects the issue. Another gotcha I encountered was making sure the “exitGame” function was a UFUNCTION().

void URoMMainMenuWidget::Construct_Implementation()
{
	Super::Construct_Implementation();

	UButton* exitButton = (UButton*) GetWidgetFromName(TEXT("exitButton"));
	exitButton->OnClicked.AddDynamic(this, &URoMMainMenuWidget::exitGame);
}

void URoMMainMenuWidget::exitGame()
{
	GetWorld()->GetFirstPlayerController()->ConsoleCommand("quit");
}

I am trying to do something like this as well but my Construct_Implementation function is not being called. Can you please detail how exactly you implemented it in your header file ? I have it declared as

virtual void								Construct_Implementation() override;

and my class derives from UUserWidget

UCLASS()
class TASKBASEDLM_API UDebugMenuWidget : public UUserWidget

Thanks !

So finally I found a solution, I was looking for this too:

.h

#include "Blueprint/UserWidget.h"
#include "MyUserWidget.generated.h"

UCLASS()
class UE4PROJECT_API MyUserWidget : public UUserWidget
{
	GENERATED_BODY()

	virtual void Construct_Implementation() ;
	
public:
	
};

.cpp

#include "MyUserWidget.h"

void MyUserWidget::Construct_Implementation()
{
	UE_LOG(LogTemp, Warning, TEXT(-------Construct-----"));
}

Hope this will help

(Additional information barisatamer)