I am trying to display a widget using pure C++.
So far I have done the following:
-
Create a custom class inherited from UUserWidget
-
Override NativeConstruct like this:
void UMinimapWidget::NativeConstruct()
{
Super::NativeConstruct();UCanvasPanel* panel = WidgetTree->ConstructWidget<UCanvasPanel>(); WidgetTree->RootWidget = panel; testWidget = WidgetTree->ConstructWidget<UButton>(); testWidget->OnClicked.AddDynamic(this, &UMinimapWidget::Test); panel->AddChildToCanvas(testWidget);
}
-
Create an instance of the widget in my player controller’s BeginPlay:
void AZyndanPlayerController::BeginPlay()
{
minimapWidget = CreateWidget(this);
} -
Try to display the widget using AddToViewport in an input handler:
void AZyndanPlayerController::ToggleMinimap()
{
UE_LOG(LogTemp, Warning, TEXT(“ToggleMinimap”));if (minimapWidget != nullptr) { if (minimapWidget->IsInViewport()) { UE_LOG(LogTemp, Warning, TEXT("Removing from viewport")); minimapWidget->RemoveFromViewport(); } else { UE_LOG(LogTemp, Warning, TEXT("Adding to viewport")); minimapWidget->AddToViewport(0); } }
}
The problem is that on the first invocation of this function seemingly nothing happens, however if I trigger it two more times (so RemoveFromViewport gets called and then AddToViewport again) the widget that I expect to see appears in the left top corner.
I also tested doing AddToViewport → RemoveFromViewport → AddToViewport in the same handler and it works the fist time then.
I was wondering what sort of magic happens in RemoveFromViewport that I need to call so that AddToViewport works properly for my widget?