Launch a Blueprint Widget from C++ code

I am looking to launch a Blueprint Widget with a custom class (followed this tutorial) from my C++ code – specifically when the player is facing an item, and presses a ‘Use’ key the Widget pops up – but cannot seem to get this to work.

void AProtagonist::Take(){
	if (GetItemFocus()){
       // Trigger an existing BP Widget
	}

}

I have already Googled extensively for the answer (ie here and here seemed like the should work but didn’t) and haven’t been able to find something that works for me yet, any help would be greatly appreciated.

Easiest and quite comftible to use (since it creates some soft of interface) way to for bidriectional BP and C++ communication, is to create C++ base class with things you want to have in C++ and then make blueprint that based of it

So create new class based of UUserWidget, put property variables for widgets you want to control, now create widget BP based of that class or change existing BP class in “Blueprint Settings”. After that go to defaults of BP and set variables you made with widgets that you placed in that BP. Now you can get current user widget that is displayed in viewport and control widget in it via variables you made.

Okay, so, at this point I have most of that – I have a UUserWidget called ‘Examine’ and a Blueprint based off that called ‘NewWidgetBlueprint’ what I want to do is set it so that when I press a key and trigger the above Take() method ‘NewWidgetBlueprint’ pops up. I’d rather keep that triggering in C++ (if possible) because the Take() method does a few other things.

I’ve been trying variations on this code in the Take method:

FStringClassReference MyWidgetClassRef(TEXT("/Game/NewWidgetBlueprint.NewWidgetBlueprint"));
		UClass* MyWidgetClass = MyWidgetClassRef.TryLoadClass<UExamine>();
		UExamine *widget = CreateWidget<UExamine>(()->GetFirstPlayerController(), MyWidgetClass);
		widget->AddToViewport();

But no joy so far. Any thoughts?

1 Like

I would like an answer to this as well. I am trying something like this:

UObject* something = StaticLoadObject(UObject::StaticClass(), nullptr, pathToBlueprint);
UBlueprint* bp = Cast(something);
TSubclassOf WidgetTemplate;
WidgetTemplate = (UClass*)bp->GeneratedClass;

	 // problem is,  TSubclassOf<class UObject>  and TSubclassOf<class UUWidget don't work together> 

	UCardWidget * Widget = dynamic_cast<UCardWidget*>(UWidgetBlueprintLibrary::Create((), WidgetTemplate, ()->GetFirstPlayerController()));

i tried it and it worked. thankyou bro.

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