[C++] Create Widget

Hi there, are you asking how to spawn a UMG widget in c++ code? I am doing a bit of this, so I can give our artists control over looks and layout, but have control over logic and interfacing with things like the online subsystem etc.

Anyway I will just give you the basics here, let me know if you need any more. I am storing mine currently on the player controller. You want a reference to the blueprint and then the instance you create.

UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = UI)
TSubclassOf<UUserWidget> WidgetTemplate;

UPROPERTY()
UUserWidget* WidgetInstance;

Then you create like so:
if (WidgetTemplate)
{
if (!WidgetInstance)
{
WidgetInstance = CreateWidget(this, WidgetTemplate);
}

	if (!WidgetInstance->GetIsVisible())
	{
		WidgetInstance->AddToViewport();
	}		
}

That will get it showing up.

Now to do the Input and Cursor parts:

FInputModeUIOnly Mode;
Mode.SetWidgetToFocus(WidgetInstance->GetCachedWidget());
SetInputMode(Mode);
bShowMouseCursor = true

When you are done don’t forget to reset the input mode back to game , hide the cursor and remove the widget

WidgetInstance->RemoveFromViewport();
WidgetInstance = nullptr;
FInputModeGameOnly GameMode;
SetInputMode(GameMode);
FSlateApplication::Get().SetFocusToGameViewport();
bShowMouseCursor = false;

I have only just started working with using UMG widgets in C++ (Before just slate) so I’ve found it a bit of a headache at times, especially with input and focus. So feel free to ask questions or let me know any little interesting issues/behaviours you run into.

Note: You can create your own class based on UUserWidget and then add custom behaviour at that level too, you just need to reparent the blueprint when in the UMG editor.

2 Likes