Create A UWidget At Runtime


UE4’s built-in blueprint function ‘CreateWidget’ only allows you to specify UUserWidgets, so to add something basic like a button, border or text at runtime, you have to create a custom UUserWidget to wrap it - very inefficient. Luckily, there’s a ConstructWidget() function in C++ that can easily be exposed to blueprints.

Make sure you’ve got a BP/C++ project, then create a blueprint function library C++ class.

Code

Add this to the .h file:

	/*
	Creates a base UWidget (text, border, image, etc) at runtime.
	*/
	UFUNCTION(BlueprintCallable, Category = "UMG")
	static UWidget* CreateUWidget(UUserWidget *InWidget, TSubclassOf<UWidget> WidgetToCreate);

And this to the .cpp:

UWidget * UWidgetFunctions::CreateUWidget(UUserWidget * InWidget, TSubclassOf<UWidget> WidgetToCreate)
{
	if ((!InWidget) || (!WidgetToCreate))
	{
		return nullptr;
	}

	UWidget *CreatedWidget = InWidget->WidgetTree->ConstructWidget<UWidget>(WidgetToCreate);
	return CreatedWidget;
}

image

It works the same as CreateWidget, in that you’ll need to add it to something after creation, in the same UUserWidget that it was created in (InWidget). So you’ll normally use it like this:

image

Videogames

Hey, do you like videogames? If so please check out my game Grab n' Throw on Steam, and add it to your wishlist. One gamemode is like golf but on a 256 km^2 landscape, with huge throw power, powerups, and a moving hole. Another is like dodgeball crossed with soccer except instead of balls you throw stacks of your own teammates. And there's plenty more!

See full gameplay on Steam!

UE4 

See also