Problem creating UI using C++

Hello everyone,

I’m trying to create my widgets in C++ in the NativeConstruct method. Here’s what I have so far:

void UUIController::NativeConstruct()
{
    Super::NativeConstruct();
    UHorizontalBox *panel = WidgetTree->ConstructWidget<UHorizontalBox>();
    WidgetTree->RootWidget = panel;
    for (int i = 0; i < towerInfos.Num(); i++)
    {
        FTowerInfo *current = &towerInfos[i];
        if (towerWidget)
        {
            UUserWidget *newWidget = WidgetTree->ConstructWidget<UUserWidget>(towerWidget);
            if (newWidget)
            {
                UE_LOG (LogTemp, Warning, TEXT ("Instantiating New Widget."));
                panel->AddChildToHorizontalBox(newWidget);
                UCallbackButton *button = (UCallbackButton*)newWidget->GetWidgetFromName("MyButton");
                if (button)
                {
                    button->Initialize (FString::FromInt(i));
                    button->buttonCallback.AddUObject(this, &UUIController::OnButtonClicked);
                    UTextBlock *text = (UTextBlock*)button->GetChildAt(0);
                    if (text && current)
                    {
                        text->SetText(FText::FromString(current->name));
                    }
                }
            }
        }
    }
}

My widgets are being correctly instantiated using WidgetTree->ConstructWidget and towerWidget is set through a blueprint that inherits from UUIController.

In my Pawn I’m creating the widget in the BeginPlay method:

void ACameraMovementController::BeginPlay()
{
	Super::BeginPlay();
    SpawnEntity ();
    if (uiController)
    {
        UUIController *controller = CreateWidget<UUIController>(GetWorld(), uiController);
        if(controller)
        {
            controller->AddToViewport();
        }
    }
}

I get no error while on play mode. The widgets simply don’t appear.

Is there a quick solution for this? Maybe am I missing something?

Thank you for your attention.

When I replace the line

UUserWidget *newWidget = WidgetTree->ConstructWidget<UUserWidget>(towerWidget);

by

UUserWidget *newWidget = CreateWidget<UUserWidget>(towerWidget);

and

panel->AddChildToHorizontalBox(newWidget);

by

newWidget->AddToViewport();

It works. Of course I don’t get the desired effect of all my widets horizontally laid out. And I can’t both add the widget as a child of the panel and to the viewport. It throws an error in real time.

Any tips on how to solve this would be much appreciated.

Solved it by moving the code from void NativeConstruct to bool Initialize.