Cast UClass to UUserWidget


Add UMG as public depedency :wink:
Include should Blueprint/UserWidget.h
You need add Slate and SlateCore too for your build as public depedency

This may help you.

i wanna write a C++ function library, it contain a function called CreateAndAddWidget

.h file

UFUNCTION(BlueprintCallable, Category = "LBP/User Interface")
		UClass* CreateAndAddWidget(APlayerController* OwningPlayer, TSubclassOf<class UUserWidget> UserWidgetClass, int ZOrder = 1);

.cpp file

UClass* ULanslotBP::CreateAndAddWidget(APlayerController* OwningPlayer, TSubclassOf<class UUserWidget> UserWidgetClass, int ZOrder)
	UClass* wid = CreateWidget<UClass>(OwningPlayer, UserWidgetClass->GetClass());
	UUserWidget* a = Cast<UUserWidget>(wid);

i cannot cast uclass to uuserwidget, so i cannot call AddToViewport.
Could you help me ?Or show me a new way?

Hey !
Your solution is totally wrong.
You try to use template, but your function isnt templatized, uclass return is useless, return UUserWidget instead of UClass… GetClass isnt needed…

Of course you can use template class function, but for this first read how templates works: C++ Templates

Anyway i highly recommend to do this in way:


UUserWidget* CreateAndAddWidget(APlayerController* OwningPC, TSubclassOf<UUserWidget> WidgetClass;


UUserWidget* YourClass::CreateAndAddWidget(APlayerController* OwnerPC, TSubclassOf<UUserWidget> WidgetClass)
       return nullptr;

   UUserWidget* wid = CreateWidget<UUserWidget>(OwnerPC, WidgetClass);


  return wid;

In this case you dont need cast and every widget is based on uuserwidget, so safe to give back uuserwidget :slight_smile:

thanks for your answer;
but i got some errors;