# \[TUTORIAL/SNIPPET\] Creating a UMG Widget in C++, and delegate example

**URL:** <https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903>\
**Category:** Programming & Scripting\
**Tags:** unreal-engine\
**Created:** [November 25, 2014, 3:24pm UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903 "2014-11-25T15:24:03Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![anonymous\_user\_6334e343](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@anonymous\_user\_6334e343](https://forums.unrealengine.com/u/anonymous_user_6334e343)\
**Post date:** [November 25, 2014, 3:24pm UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/1 "2014-11-25T15:24:03Z")

</div>

Hey everyone i just wanted to post this quik tutorial about creating widgets in C++.  
For a tutorial on How to extend a UUserWidget:: for UMG in C++ see link.

Now doing this is prety straight forward except for when dealing with multiplayer.  
And i spent some houers trying diferent solution and this is what i came up with.

**1 In your player controller class add two new member variabels like this.**

```auto

	// The class that will be used for the players Inventory UI
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Player, HUD and UI")
		TSubclassOf<class UInventoryUserWidget> InventoryUIClass;

	// The instance of the players Inventory UI Widget
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Player, HUD and UI")
		class UInventoryUserWidget* InventoryWidget;

```

**2 Override the BeginPlay() method in your Player Controller class.**

```auto

void AMyPlayerController::BeginPlay()
{
	Super::BeginPlay();

	// Only create the UI on the local machine (dose not excist on the server.)
	if (IsLocalPlayerController())
	{
		if (InventoryUIClass) // Check the selected UI class is not NULL
		{
			if (!InventoryWidget) // If the widget is not created and == NULL
			{
				InventoryWidget = CreateWidget<UInventoryUserWidget>(this, InventoryUIClass); // Create Widget
				if (!InventoryWidget )
				    return;
				InventoryWidget->AddToViewport(); // Add it to the viewport so the Construct() method in the UUserWidget:: is run.
				InventoryWidget->SetVisibility(ESlateVisibility::Hidden); // Set it to hidden so its not open on spawn.
			}
		}
	}
}

```

**3 Open and close inventory UI example.**

```auto

void AMyPlayerController::ToggleInventory()
{
	if (bShowingInvetory)
		bShowingInvetory = false;
	else
		bShowingInvetory = true;

	if (InventoryWidget)
	{
		if (bShowingInvetory)
		{
			InventoryWidget->SetVisibility(ESlateVisibility::Visible);
		}
		else {
			InventoryWidget->SetVisibility(ESlateVisibility::Hidden);
		}
	}
}

```

Thats it! 🙂  
Now if you are wondering way I don`t create it on the server, how do you have server \> client behavior?  
I do this by creating delegates on the Player Controller and bind them in the Contruct\_Implementation() method, that in turns call a “BlueprintImplementableEvent” to notifie the widget it self so it can behave accordingly.  
_Note: OnPlayerPickupItem delegate is called from server to client using a Remote Procedure Call (RPC)_

is a example of this.

```auto

void UInventoryUserWidget::Construct_Implementation()
{
	Super::Construct_Implementation();

	AMyPlayerController* PC = CAST_TO_MY_PC(GetOwningPlayer());
	if (PC)
	{
		// Calls CallPlayerPickupItem() that in turn calls the "BlueprintImplementableEvent" on OnPlayerPickedItem()
		PC->OnPlayerPickupItem.RemoveDynamic(this, &UInventoryUserWidget::CallPlayerPickupItem); // Remove the delegate before binding it. (Its always safe to unbind a delegate.)
		PC->OnPlayerPickupItem.AddDynamic(this, &UInventoryUserWidget::CallPlayerPickupItem); // Bind the delegate from the PC that calls the BlueprintImplementableEvent.
	}
}

```

Hope this was helpful i spent some time on the crash i got when not checking for IsLocalPlayerController().  
And tought it might be a nice share for anyone else having the issue.

---

<div class="post-metadata">

**Author:** ![Elvince](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@Elvince](https://forums.unrealengine.com/u/Elvince)\
**Post date:** [December 19, 2014, 10:20am UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/2 "2014-12-19T10:20:00Z")

</div>

Thanks for this.  
I think for people that are not familiar with Delegate & BlueprintImplementableEvent, you may just update your sample for the delegate part with the .H delegate & BlueprintImplementableEvent declaration so people understand how to setup this.

You can also put the RPC function to demonstrate how you called the delegate.

in all case, it’s clearly an useful information.

---

<div class="post-metadata">

**Author:** ![user\_5a6bfd32b1a7349a5f1413349459e191f21a52a9f5b6c819e33abd](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@user\_5a6bfd32b1a7349a5f1413349459e191f21a52a9f5b6c819e33abd](https://forums.unrealengine.com/u/user_5a6bfd32b1a7349a5f1413349459e191f21a52a9f5b6c819e33abd)\
**Post date:** [March 29, 2015, 7:52am UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/3 "2015-03-29T07:52:14Z")

</div>

Hi! .

Thanks for yours tutorial.  
I did your tutorial, but i can’t see widget  
\*\*\*\*because InventoryUIClass is null pointer value.

When does InventoryUIClass set by pointer value?

What’s wrong?

I think that widget blueprint not executed.

How can i call widget blueprint?

1. Myproject name is widgettest2.

**\<widgettest2.h\>**

```auto

#ifndef __WIDGETTEST2_H__
#define __WIDGETTEST2_H__

#include "EngineMinimal.h"

//UMG
#include "Runtime/UMG/Public/UMG.h"
#include "Runtime/UMG/Public/UMGStyle.h"
#include "Runtime/UMG/Public/Slate/SObjectWidget.h"
#include "Runtime/UMG/Public/IUMGModule.h"
#include "Runtime/UMG/Public/Blueprint/UserWidget.h"
//

#endif

```

**\<UInventoryWidget.h\>**

```auto

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "Blueprint/UserWidget.h"
#include "UInventoryWidget.generated.h"

/**
 * 
 */
UCLASS()
class WIDGETTEST2_API UUInventoryWidget : public UUserWidget
{
	GENERATED_BODY()
	

	
	
};

```

**\<UInventoryWidget.cpp\>**

```auto

// Fill out your copyright notice in the Description page of Project Settings.

#include "widgettest2.h"
#include "UInventoryWidget.h"

```

**\<MyPlayerController.h\>**

```auto

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "GameFramework/PlayerController.h"
#include "MyPlayerController.generated.h"

/**
 * 
 */
UCLASS()
class WIDGETTEST2_API AMyPlayerController : public APlayerController
{
	GENERATED_BODY()

public:
	virtual void BeginPlay() override;

public:
		// The class that will be used for the players Inventory UI
		UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Player, HUD and UI")
		TSubclassOf<class UUInventoryWidget> InventoryUIClass;

	// The instance of the players Inventory UI Widget
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Player, HUD and UI")
	class UUInventoryWidget* InventoryWidget;

	
	
};

```

**\<MyPlayerController.cpp\>**

```auto

// Fill out your copyright notice in the Description page of Project Settings.

#include "widgettest2.h"
#include "MyPlayerController.h"
#include "UInventoryWidget.h"

void AMyPlayerController::BeginPlay()
{
	Super::BeginPlay();

	// Only create the UI on the local machine (dose not excist on the server.)
	if (IsLocalPlayerController())
	{
		**if (InventoryUIClass) // Check the selected UI class is not NULL** {
			if (!InventoryWidget) // If the widget is not created and == NULL
			{
				InventoryWidget = CreateWidget<UUInventoryWidget>(this, InventoryUIClass); // Create Widget
				if (!InventoryWidget)
					return;
				InventoryWidget->AddToViewport(); // Add it to the viewport so the Construct() method in the UUserWidget:: is run.
				InventoryWidget->SetVisibility(ESlateVisibility::Hidden); // Set it to hidden so its not open on spawn.
			}
		}
	}
}

```

**\<MyWidget - Widget Blueprint\>**

 ![MyWidget1.PNG](https://d3kjluh73b9h9o.cloudfront.net/original/3X/5/f/5fb278aa9a98b158dea079210fc859de2a5849f9.png)

 ![MyWidget1.PNG](https://d3kjluh73b9h9o.cloudfront.net/original/4X/7/8/c/78cda010ddb669cf116572ee05cbd0c492b73649.png)

That’s all!!

**Help me, please.**

Engine Version : 4.7.0  
OS : Windows 7

---

<div class="post-metadata">

**Author:** ![eXi](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/exi/32/906583_2.png) [@eXi](https://forums.unrealengine.com/u/eXi)\
**Post date:** [March 29, 2015, 10:19am UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/4 "2015-03-29T10:19:02Z")

</div>

Hey there,

this is not my tutorial but the “TSubclassOf\<class UUInventoryWidget\> InventoryUIClass;” should be set in the Blueprint Default Value  
of your PlayerController. Go into your “PlayerController” BP and click on “Class Defaults” at the top. Make sure that you assigned  
the correct Class to the “InventoryUIClass” variable .

---

<div class="post-metadata">

**Author:** ![anonymous\_user\_02360bb5](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@anonymous\_user\_02360bb5](https://forums.unrealengine.com/u/anonymous_user_02360bb5)\
**Post date:** [April 25, 2015, 6:22pm UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/5 "2015-04-25T18:22:53Z")

</div>

Hey, if you are having issues with intellisense about not being able to open UserWidget.h you should generate visual studio files to fix it.

---

<div class="post-metadata">

**Author:** ![cridia](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/cridia/32/772487_2.png) [@cridia](https://forums.unrealengine.com/u/cridia)\
**Post date:** [June 3, 2015, 11:57pm UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/6 "2015-06-03T23:57:57Z")

</div>

This looks like an awesome tutorial! Now, I have a question; would it be possible to have the HUD class be responsible for spawning the widgets? My current implementation causes my game to freeze if I put it into the beginplay function. The reason I want to do this is because for certain functions in my widgets, I want access to canvas functions like project or deproject.

---

<div class="post-metadata">

**Author:** ![Vaclav.Jarko](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@Vaclav.Jarko](https://forums.unrealengine.com/u/Vaclav.Jarko)\
**Post date:** [June 4, 2015, 10:02pm UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/7 "2015-06-04T22:02:34Z")

</div>

Pointless if its not working

---

<div class="post-metadata">

**Author:** ![Kochab](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@Kochab](https://forums.unrealengine.com/u/Kochab)\
**Post date:** [July 19, 2015, 2:30pm UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/8 "2015-07-19T14:30:32Z")

</div>

> [@Raikoh;279201](#):
>
> Hey, if you are having issues with intellisense about not being able to open UserWidget.h you should generate visual studio files to fix it.

Thanks, that worked for me. For anyone who doesn’t know, you generate visual studio files by going to your project folder, right clicking the .uproject file, and clicking “generate visual studio project files”.

---

<div class="post-metadata">

**Author:** ![Kochab](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@Kochab](https://forums.unrealengine.com/u/Kochab)\
**Post date:** [July 19, 2015, 4:10pm UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/9 "2015-07-19T16:10:15Z")

</div>

Can anyone help me with this? I am getting an error and don’t know what it means:

error C2228: left of ‘.\_\_Internal\_RemoveDynamic’ must have class/struct/union  
error C2228: left of ‘.\_\_Internal\_AddDynamic’ must have class/struct/union

```auto

if (PC)
{
	// Calls CallPlayerPickupItem() that in turn calls the "BlueprintImplementableEvent" on OnPlayerPickedItem()
        PC->UI_UpdateScore.RemoveDynamic(this, &USHud::CallUpdateScore); // Remove the delegate before binding it. (Its always safe to unbind a delegate.)
	PC->UI_UpdateScore.AddDynamic(this, &USHud::CallUpdateScore); // Bind the delegate from the PC that calls the BlueprintImplementableEvent.
}

```

---

<div class="post-metadata">

**Author:** ![gozu](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/gozu/32/869945_2.png) [@gozu](https://forums.unrealengine.com/u/gozu)\
**Post date:** [September 14, 2015, 4:12am UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/10 "2015-09-14T04:12:01Z")

</div>

Thanks for this man this helped me perfectly.

---

<div class="post-metadata">

**Author:** ![gozu](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/gozu/32/869945_2.png) [@gozu](https://forums.unrealengine.com/u/gozu)\
**Post date:** [September 14, 2015, 4:16am UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/11 "2015-09-14T04:16:34Z")

</div>

> [@cridia;304414](#):
>
> This looks like an awesome tutorial! Now, I have a question; would it be possible to have the HUD class be responsible for spawning the widgets? My current implementation causes my game to freeze if I put it into the beginplay function. The reason I want to do this is because for certain functions in my widgets, I want access to canvas functions like project or deproject.

Freeze like lock up, or just pause for a moment while it creates it?

It should work fine from any class (i have done it from gameinstance, playercontroller, and a gamemode for various things)

If it is doing it when it creates it, the best way around this is to create the widget on begin play, and hide it, then unhide it when you wish to show it. this is what im doing from player controller and i do not get a pause.)

My hud is actually a blueprint based off my c++ hud class, that attaches a widget in there.  
Something like that might do what you want. 🙂

---

<div class="post-metadata">

**Author:** ![anon65365138](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@anon65365138](https://forums.unrealengine.com/u/anon65365138)\
**Post date:** [September 3, 2016, 8:50am UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/12 "2016-09-03T08:50:30Z")

</div>

Just in case those who face InventoryUIClass is being NULL like above replies and myself, there is a solution thx to .

Instead of TSubclassOf, use TAssetSubclassOf with LoadSynchronous();

is new code

```auto

UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Player, HUD and UI")
	TAssetSubclassOf<class UInventoryUserWidget> InventoryUIClass;

	// The instance of the players Inventory UI Widget
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Player, HUD and UI")
	class UInventoryUserWidget* InventoryWidget;

```

```auto

void AMyPlayerController::BeginPlay()
{
	Super::BeginPlay();

	// Only create the UI on the local machine (dose not excist on the server.)
	if (IsLocalPlayerController())
	{
		
		if (!InventoryWidget) // If the widget is not created and == NULL
		{
			InventoryWidget = CreateWidget<UInventoryUserWidget>(this, InventoryUIClass.LoadSynchronous()); // Create Widget
			if (!InventoryWidget )
			    return;
			InventoryWidget->AddToViewport(); // Add it to the viewport so the Construct() method in the UUserWidget:: is run.
			InventoryWidget->SetVisibility(ESlateVisibility::Hidden); // Set it to hidden so its not open on spawn.
		}
		
	}
}

```

after that, make sure your GameMode has BP version of your controller class. Yes, you need your own GameModeBP with BP version of your controller class.

> **[Trying WCode's UMG Widget c++ and... TSubclassOf Causing trouble...](https://forums.unrealengine.com/showthread.php?121639-Trying--s-UMG-Widget-c-and-TSubclassOf-Causing-trouble)**
>
> Just like one of replies, it happened to me that TSubclassOf InventoryUIClass not being initialized (still NULL)… I did googling or being experiemental… I have been grasping hard time about what is TSubclassOf\<\> exactly… and how do I...

this is the thread how I got to know the solution.

---

<div class="post-metadata">

**Author:** ![anonymous\_user\_101bca4f](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@anonymous\_user\_101bca4f](https://forums.unrealengine.com/u/anonymous_user_101bca4f)\
**Post date:** [November 11, 2018, 3:55am UTC](https://forums.unrealengine.com/t/tutorial-snippet-creating-a-umg-widget-in-c-and-delegate-example/15903/13 "2018-11-11T03:55:52Z")

</div>

Thanks my brudda for posting this 🙂
