How would I recreate this in C++?

So as you can see I am creating a widget in a blueprint (because it is displaying variables from that blueprint) and I would like to know how you can convert this into C++?

header

	UPROPERTY(EditAnywhere,BlueprintReadWrite)
	TSubclassOf<UUserWidget> UserInterfaceClass;

	UPROPERTY(EditAnywhere, BlueprintReadWrite)
	UUserWidget* BuildingProductionRef;

cpp

	if (UserInterfaceClass != nullptr) {
		BuildingProductionRef = CreateWidget<UUserWidget>(GetWorld(), UserInterfaceClass);
//		BuildingProductionRef->AddToViewport(9999); if you want to add it to viewport

	}

in your build file you need to add UMG
example:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput","UMG" });
1 Like

where do I say what kind of widget i’m creating because if you look in the BP, it says i’m creating “Construction Widget” but I notice it doesn’t say that in the c++

this is the full BP with the beginplay

Screenshot 2023-05-10 172551

This is what we have been using to add a specific UserWidget to the HUD.

// in .h file
UPROPERTY()
  UDeadHUDWidget* _deadHudWidget = nullptr;

// in .cpp file
void APrimaryHUD::LoadBlueprint_Dead()
{
  // append "_C" to the hud blueprint name, why, because Unreal
  FSoftClassPath deadClassReference(TEXT("/Game/Blueprints/HUD/Dead.Dead_C")); 
  UClass* deadHudClass = deadClassReference.TryLoadClass<UUserWidget>();
    if (deadHudClass != nullptr)
    {
      // loaded the blueprint, save reference, and add it to the viewport
      UUserWidget* userWidget = CreateWidget<UUserWidget>(GetWorld(), deadHudClass);
      _deadHudWidget = Cast<UDeadHUDWidget>(userWidget);
      if (_deadHudWidget != nullptr)
      {
        _deadHudWidget->AddToViewport();
      }
    }
}

So this is loading a HUD widget that is used when the player is dead. We manage all the HUD blueprints in the HUD.cpp class. Thus nothing outside of the HUD knows about specific widgets, it only knows about the HUD class.

One improvement on the TODO list is making there generic by just passing in the string path of the widget.

One thing to note is the “Z” order of widgets is the order they are added in code.

1 Like

so I have to set the variable for the widget in the cpp HUD (or header file?) and then create the widget in the other cpp file?

For persistent variables in a class, usually you define them in the .h file and make them a UPROPERTY() so they don’t get garbage collected.

If the variable doesn’t need to be used again then you could just define in the .cpp function.

Ok so I guess my problem really isn’t how to create a widget but how to get that widget reference and create it…

Why do UserInterfaceCLass?

UserInterfaceCLass is just the name of the variable that holds the created widget. You can name it however you want :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.