Create widget in pure C++

First you create a widget that extends UUserWidget.

class UMyUserWidget : public UUserWidget

Next you override the NativeConstruct method.

virtual void NativeConstruct() override;

In your .cpp file you implement NativeConstruct.

void UMyUserWidget::NativeConstruct()
{
    Super::NativeConstruct();

    // Bind delegates here.
}

In your PlayerController class create and display the widget.

UserInterface = CreateWidget<UMyUserWidget>(this, UMyUserWidget::StaticClass());
FInputModeGameAndUI Mode;
Mode.SetLockMouseToViewport(true);
Mode.SetHideCursorDuringCapture(false);
SetInputMode(Mode);
UserInterface->AddToViewport(9999); // Z-order, this just makes it render on the very top.

Now that you have created your base widget in C++ you can start adding components to it. It is extremely important to note that widget components are also widgets. This means you create them in the exact same way you create your UUserWidget.

In your header file define a widget type. In this case I’ll define a UButton.

UPROPERTY()
UButton* ExampleButton;

In your CPP file you will instantiate that button.

UPanelWidget* RootWidget = Cast<UPanelWidget>(GetRootWidget());

ExampleButton = WidgetTree->ConstructWidget<UButton>(UButton::StaticClass(), TEXT("MyButtonName")); // The second parameter is the name and is optional.
ExampleButton->OnClicked.AddDynamic(this, &MyUserWidget::OnButtonClicked); // Example click binding.
RootWidget->AddChild(ExampleButton);

There are, of course, more steps in this like setting the padding, color, and other properties. It is best that you give your widgets names so you can find them later using using WidgetTree->FindWidget(TEXT(“WIDGET_NAME”)).

10 Likes