(UMG/C++) Why does AddToViewport on a custom widget work only after RemoveFromViewport is called?

I am trying to display a widget using pure C++.

So far I have done the following:

  1. Create a custom class inherited from UUserWidget

  2. 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);
    

    }

  3. Create an instance of the widget in my player controller’s BeginPlay:

    void AZyndanPlayerController::BeginPlay()
    {
    minimapWidget = CreateWidget(this);
    }

  4. 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 AddToViewportRemoveFromViewportAddToViewport 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?

Hey mechkg, I had the same problem, did you find a solution?

Ola, I’ve had the same problem with just not showing, and even if I do AddToViewport, RemoveFromViewport and add again it still doesn’t work.
Have you had any luck finding the solution?