UUserWidget class in Unreal Engine

The user widget is extensible by users through the WidgetBlueprint.

UUserWidget class is a base class of Blueprint UI widgets accessible through User InterfaceWidget Blueprint.

Inheritance Hierarchy

List of all variables, constructors and functions declared by the class is available in the official documentation that is generated right from the C++ class code.

As always, there is possible to create a subclass based on UUserWidget C++ class and then inherit a Blueprint Widget from it. However, it's not necessary till the UI logic is going to get super complicated. in most cases, there's possible to skip the c++ subclass and create the blueprint widget right the Blueprint by inheriting right from the default UUserWidget class. It can by done by pressing right mouse button in the content window and selecting User InterfaceWidget Blueprint. Newly created Blueprint widget should got a name starting with WBP_ prefix.

There are various ways to work with User Widgets, check a way of architecture using reusable components at this guide to UGM for instance.

Blueprint User Widgets stands to start with WBP_ name prefix.

Blueprint UserWidget Graph nodes

  • Event Pre Construct - an equivalent of Construct script in C++
  • Event Construct - an equivalent of Begin Play in C++
  • Event Tick - an Equivalent of Tick function

Adding a Blueprint Widget into the viewport

Spawning Blueprint widgets onto the screen is simple in Blueprint code as well as in the C++ code.

Option 1: In Blueprint

Blueprint widget can be placed into the viewport through Bluperint nodes Create WidgetAdd to Viewport. Once the widget is not necessary anymore, it can be removed with BP node Remove from Parent.

Option 2: In C++ code

Spawning UUserWidgets through C++ requires to set a public dependency for UMG. It can be done in the projects's .Build.cs file, by attaching "UMG" module into PublicDependencyModuleNames.AddRange String array on the line 11. This dependency allows us to use #include "Blueprint/UserWidget.h" without getting compilation errors.

// .h file
UPROPERTY(EditAnywhere)
TSubclassOf<class UUserWidget> LoseScreenClass;
// .cpp file
#include "Blueprint/UserWidget.h"
UUserWidget* LoseScreen = CreateWidget(this, LoseScreenClass);
if(LoseScreen != nullptr) LoseScreen->AddToViewport();

Removing userWidget from Viewport

LoseScreen->RemoveFromViewport();

Make C++ variable accessible from the Bluepring Widget

// AExampleCharacter - .h file
private:
   UPROPERTY()
   float Health;
public:
   UFUNCTION(BlueprintPure)
   float GetHealthPercent() const;

// .cpp file
float AExampleCharacter::GetHealthPercent() const
{
	return Health / MaxHealth;
}

in Blueprint User Widget, there's an option Bind for progress bar within which there's possible to bind the state of UI progress bar value with the C++ Health variable value through Cast To BP node.