How to construct UMG widget in C++?

I am trying to construct UMG widget in C++ and create simple button inside of it:

void UMyUserWidget::NativeConstruct()
{
	Super::NativeConstruct();
	
	auto MyCanvas = WidgetTree->ConstructWidget<UCanvasPanel>(UCanvasPanel::StaticClass());
	auto MyButton = NewObject<UButton>(this);
	MyCanvas->AddChildToCanvas(MyButton);
	WidgetTree->Modify();
	WidgetTree->RootWidget = MyCanvas;
}

After adding this widget to viewport, this method is called, but i dont see any button on the screen.

I got my button visible on screen by moving this code from NativeConstruct to Initialize function. But after recompile i am getting CanvasPanel is not packaged exception and crash on hot-reload.

void UMyUserWidget::Initialize()
{
Super::Initialize();

// Initialize called after hot-reload with WidgetTree = NULL, skip this unexpected call, or you will get CanvasPanel is not packaged error.
if(WidgetTree)
{
     auto MyCanvas = WidgetTree->ConstructWidget<UCanvasPanel>(UCanvasPanel::StaticClass());
     auto MyButton = WidgetTree->ConstructWidget<UButton>(UButton::StaticClass());
     MyCanvas->AddChildToCanvas(MyButton);
     WidgetTree->RootWidget = MyCanvas;
}

 }

Well, now i got UMG widget constructed and visible, but i dont know yet how to do that AFTER Initialize call, for instance inside NativeConstruct function, which is called after Initialize.

I’ve got it working dinamically, but i still have to set WidgetTree->RootWidget = MyCanvas inside Initialize function:

             bool UMyUserWidget::Initialize()
              {
                  bool b = Super::Initialize();
    
    // more correct way to avoid error. than in original post.
            if(!HasAnyFlags(RF_ClassDefaultObject) )
             {
// root have to be initialized in Initialize function, otherwise it will not work, donno exactly why.
                  MyCanvas = WidgetTree->ConstructWidget<UCanvasPanel>();
                  WidgetTree->RootWidget = MyCanvas;
             }
        
        return b;
              }
            
              void UMyUserWidget::NativeConstruct()
              {
                  Super::NativeConstruct();
             
                  auto MyButton = WidgetTree->ConstructWidget<UButton>();
                  MyCanvas->AddChildToCanvas(MyButton);
              }

Where is the WidgetTree?

include “Blueprint/WidgetTree.h”

According to UWidgetTree | Unreal Engine Documentation

1 Like

I do not know about him, but I am looking how to initialize the WidgetTree.