Add a widget to an actor via c++

Hi guys,

im trying to add a UWidgetComponent to my actor. However as soon as i try to initialize that object by doing this:

Widget= CreateDefaultSubobject<UWidgetComponent>(TEXT("Widget1"));

I’ll get the error:

c:\program files\unreal engine\4.7\engine\source\runtime\coreuobject\public\uobject\UObject.h(81): error C2440: 'static_cast' : cannot convert from 'UObject *' to 'UWidgetComponent *'

Any idea how to fix that? I’m a bit confused as well since, according to the api doc, UObject is a parent class of UObjectComponent so the casting should work.

Or is that not the right way to initialize that object?

Regards

Hello,

Please make sure that you have the appropriate include in your header file:

#include "Components/WidgetComponent.h"

Hope this helped!

Cheers!

Hi,

thanks for answering. However, if I am including this into my header file i’ll get another error.

.h

#include "Components/WidgetComponent.h"

UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = HUD)
class UWidgetComponent* Widget;

.cpp

Widget= CreateDefaultSubobject<UWidgetComponent>(TEXT("Widget"));

error

C:\Program Files\Unreal Engine\4.7\Engine\Source\Runtime\UMG\Public\Components/WidgetComponent.h(72): error C2065: 'FWidgetAndPointer' : undeclared identifier
C:\Program Files\Unreal Engine\4.7\Engine\Source\Runtime\UMG\Public\Components/WidgetComponent.h(72): error C2923: 'TArray' : 'FWidgetAndPointer' is not a valid template type argument for parameter 'InElementType'

thanks in advance!

P.S.: Is there an easy way to tell when to inculde stuff? It’s kinda hard to tell if you need to. Obviously you can’t rely on error messages :confused:

I tried a different approach which lead me to where I am now.
Actually it turned out exactly as I wanted It to be:

.h

// The class that will be used for the Items Nameplate
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = UI)
TSubclassOf<class UUserWidget> NameplateUIClass;

// The instance of the players Inventory UI Widget
UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = UI)
class UUserWidget* NameplateWidget;

.ccp

if (NameplateUIClass)
	{
		if (!NameplateWidget)
		{
			NameplateWidget = CreateWidget<UUserWidget>(GetWorld()->GetGameInstance(), NameplateUIClass);
			if (!NameplateWidget)
			{
				return;
			}

			NameplateWidget->AddToViewport();
			NameplateWidget->SetVisibility(ESlateVisibility::Hidden);
		}
	}

This allows me to control the widget via code and I may use the editor to design the widget itself. You have to create that widget(class) within the editor however. Values can be exchanged via blueprint get and set.

Nevertheless I ran into a new problem, which is handled here : https://answers.unrealengine.com/questions/197861/why-is-uuserwidget-is-not-a-type-name-when-i-try-t.html