How to Add my Widget to Vertical Box? It keeps failing

for (int32 i = 0; i < 4; i++) {
UUIHUDSlotsBar* UIslotbar = NewObject<UUIHUDSlotsBar>(this, UUIHUDSlotsBar::StaticClass());
UIslotbar->SetKey(i);
SlotsBar->AddChildToVerticalBox(UIslotbar );
}

I tried to add UUIHUDSlotsBar to my SlotsBar(which is Vertical Box) but ue4 keeps crushing.

how should I fix it?

You should be creating widgets with the CreateWidget<YourWidgetClass>(…) function.

I had a problem where I was trying to add widgets to a vertical box in a loop using C++, and this post has a ton of views, so I’ll post what my fix was, in case it helps someone else.

Here I have a UI that displays character text on the HUD. The TextBlock holder class is in a BarkLineClass, like this:

	UPROPERTY(EditAnywhere, BlueprintReadWrite)
	TSubclassOf<UBarkLine> BarkLineClass;

What was happening for me was the first line would appear, but any subsequent lines would not appear.

Does not work:

	UUserWidget *Widget = CreateWidget(PlayerController, BarkLineClass, "BarkLine");
	if (UBarkLine *BarkLine = Cast<UBarkLine>(Widget))
	{
		BarkLine->Text->SetText(NewText);
		BarkContainer->AddChildToVerticalBox(Widget);
	}

Works:

	const int LineCount = BarkContainer->GetChildrenCount();
	FName LineName(FString::Printf(TEXT("BarkLine_%d"), LineCount));
	UUserWidget *Widget = CreateWidget(PlayerController, BarkLineClass, LineName);
	if (UBarkLine *BarkLine = Cast<UBarkLine>(Widget))
	{
		BarkLine->Text->SetText(NewText);
		// If the name of the widget is the same as another it will corrupt
		BarkContainer->AddChildToVerticalBox(Widget);
	}

Was about ready to climb the walls and then after some UE_LOG’s showed corruption in the widget tree, I tried creating those sequential names and it worked. Fixed!