[C++] Create Widget

How could I recreate this blueprint in C++ code. It’d be great!
I can’t seem to figure it out.

1 Like

As far as i know, UMG Widget are based on “Slate” a programming language made up by some of the Epic Games guys. They invented UMG to get rid of the C++ horror with Slate, because it’s not that easy to learn, at least not for me.

Rama made some Tutorials for Slate:

But i would recommend to stay with UMG since they made it for us, so we don’t have to use Slate.

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

Thank you, this helped us.

Slate isn’t a programing language, it’s a GUI framework.

I think it’s better to use UMG for the design part. The main reason for introducing UMG was probably to let the GUI designer focus on the layout and hiding the implementation. In this way the implementation and GUI are nicely separated.

What headers do I include to access UUserWidget?

These are the main two

#include "Runtime/UMG/Public/UMG.h"
#include "Slate.h"

Also make sure UMG, Slate and SlateCore are in your public or private dependencies in your .Build.cs

CreateWidget crashes for us when we join an existing session. Anyone else have this problem?

Hi, thanks Ben.Driehuis for the example. When I’m declaring the variables

TSubclassOf<UUserWidget> WidgetTemplate;
UUserWidget* WidgetInstance;

I get ‘Error: variable “UUserWidget” is not a type name’

I am in my PlayerController and am including

// including "Slate.h" is deprecated
#include "SlateBasics.h"
#include "Runtime/UMG/Public/UMG.h"
// maybe I need this?
#include "Runtime/UMG/Public/Blueprint/UserWidget.h"

I have added Slate to my build.cs like this:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "UMG", "Slate", "SlateCore" });

Any idea why I get the error?

Which version of unreal are you on?

I recommend UMG too, but i highly recommend to learn something about the Slate UI Framework too, because UMG = Visual Slate Editor (i just came up with this word myself :wink: ). So in order to get your widgets work as they are intended to, you should also know how the Widgets f.e. SOverlay, Boxes, etc. work.

I realize this is an old answer, but any idea why I’m getting an access violation in the CreateWidget(UWorld, UClass) tempalted function? Here is my code:

UGameSettingsWidget *MyWidget = CreateWidget<UGameSettingsWidget>(GetWorld(), UGameSettingsWidget::StaticClass());

Thanks :slight_smile:

EDIT: It happens on the line:

NewWidget->Initialize();

Had this problem. The main thing you need to understand is that you don’t create your custom widget class directly, you want to create the widget you’ve parented to that custom widget class. So instead of UGameSettingsWidget::StaticClass() you need to do something like this:

YourCustomWidgetUIClass = LoadClass<YourCustomWidget>(..., TEXT(path_to_your_widget_in_content_browser), ...);

“path_to_your_widget_in_content_browser” can be something like “Game\UI\MyWidget.MyWidget_C”.

You can find the complete syntax reference for LoadClass in the docs.

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

For anyone else who’s come across this forum post, wondering how to create UMG Widgets in C++ (like me), please take a look at the ben.ui website - it’s very well made and helped me immensely!

Additionally, it you would like to create widgets in C++ and then also use them in Blueprint again, take a look at their BindWidget article.

P.S. - Don’t forget to add UMG to you project dependencies too!

// Copyright Epic Games, Inc. All Rights Reserved.

using UnrealBuildTool;

public class YourPojectNameHere: ModuleRules
{
	public YourPojectNameHere(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput", "UMG" }); // Add "UMG" like shown here
	}
}

Edit: I’ve realized that my original post isn’t as helpful as I’d like it to be, so I’ve made this short tutorial to demonstrate how to apply it all.

  1. Create a new Unreal class that extends UUserWidget, and define the elements you want in the widget, and ensure they have a UPROPERTY specifier, UPROPERTY(EditAnywhere, meta=(BindWidget)).

  2. Build your project with your newly created widget class and then launch the project and go into the UE Editor.

  3. Navigate to whatever directory you’d like to create the widget BP in, then right click to create a new Blueprint Class, and pick the C++ UUserWidget class you just made as the parent of it (mine is named UTestWidget).

  4. Name the new Blueprint however you see fit (ex. WB_TestWidget).

  5. Double-click the new BP to open it up in the widget editor. Since only one sub-widget can be a child of the root widget, I made it a canvas panel.
    Pasted image 20240711221116

  6. You may notice that the widget cannot compile. This is because we declared those BindWidget meta specifiers in the C++ file! We now must mirror those elements inside of this widget BP by creating their respective counterparts here.

  7. With these sub-widgets added under the canvas panel, and their names changed to be the same as in the file, we can now compile the widget BP! Also, go ahead and add some stuff to the widget, so that it is noticeable when we simulate the game here in a little bit.

  8. Now back to C++ - move to your character class’s .h file and define two new class members: one for our widget’s class, and the other for an instantiated widget itself. (Note: We make the ‘widget-class’ member EditAnywhere, because we’ll have to assign it in our character’s BP later).
    Pasted image 20240711221955

  9. Override the BeginePlay() from the inherited ACharacter class, if it is not already.
    Pasted image 20240711222412

  10. Move into your character class’s .cpp file and define our two new class member’s default values as nullptr (you can do it in the initializer list or in the block itself - doesn’t matter).

  11. Then, add the BeginPlay() method definition and add an if-statement inside of it, checking if the character is currently being controller and the TestWidgetClass member is defined.
    Pasted image 20240711223137

  12. Inside of this if-statement, create the widget and add it to your character’s viewport.

  13. Sweet - we’re done with the C++ part, but there’s still one last thing to do with our character BP. Navigate back to the UE Editor and open up your character’s BP and click “Class Defaults” at the top.
    Pasted image 20240711223751

  14. In the Search bar under the “Details” panel, search for that widget-class variable we defined in our C++ character class.

  15. Change the value here from “None” to our new widget BP we made before.
    Pasted image 20240711224231

  16. Once compiled, we’re done! Now all there is, is to test the widget! Hit alt+p to simulate the game.

  17. Congrats, we did it! Next, do what you’d like with the widget - remember, we made that ‘instantiated’ widget property, TestWidget. With it, we can modify the values of the text and progress bar by defining setters to our UTestWidget class, but that’s another tutorial for another day.

I could not have made this without the aid of Lively Geek’s video, UMG Widgets with C++ in Unreal Engine 5. Please check it out and give’m a thumbs up!