CreateWidget c++

Hello. I have a c++ UUserWidget class which has variables like UTextBlock*, UButton* etc. And Blueprint widget derived from that class. Now i cant figure out how to implement this same logic in c++. I do have an Item class and also TArray of Items, i just dont know how to pass on and array element in CreateWidget Function in c++. Please help.

1 Like

Thank you so much for replying. Basically what i wanna know is how can i create widget in c++ using TArray. This is the code that i normally use when creating widget. e.g ammo widget i created.

.h

UPROPERTY(EditDefaultsOnly)
    TSubclassOf<UUserWidget> AmmoWidget;

UAmmoWidget* AmmoWidgetRef;

.cpp

if (AmmoWidget)
	{
		AmmoWidgetRef = CreateWidget<UAmmoWidget>(GetWorld(), AmmoWidget);
		if (AmmoWidgetRef)
		{
			AmmoWidgetRef->AddToViewport();
		}
	}

What i cant figure out is what is the syntax of CreateWidget function when i have TArray so that i can have the same effect in c++. Hope its making sense.

1 Like

In the meta on UPROPERTY add ExposeOnSpawn = true for the TArray.

Create your TArray in the header and add the UPROPERTY meta ExposeOnSpawn = true.

Similar to how you do it in Blueprint, you are going to want to iterate through the elements in a TArray of TSubClassOf.

So your property should become

UPROPERTY(EditDefaultsOnly)
TArray<TSubclassOf<UUserWidget>> WidgetClasses;

Then to iterate and spawn the widgets

for (auto& WidgetClass in WidgetClasses)
{
    UUserWidget* Widget = CreateWidget<UUserWidget>(GetWorld(), WidgetClass);

    if (Widget)
    {
        Widget->AddToViewport();
    }
}

In this example, the auto& keyword means that in your loop, WidgetClass will be a reference to whatever type is stored in WidgetClasses. For more information on for each loops in C++, see Range-based for loop (since C++11) - cppreference.com . If that is a bit too technical, you should get plenty of results just searching for “C++ for each loop” on Google.

Adding ExposeOnSpawn will allow you to set the values of the TArray prior to spawn, but it won’t actually create the widgets.

i think this video will be helpfull. How to Spawn/Create Widget in Unreal Engine C++ - YouTube