UI Widget doesn't disappear using "RemoveFromParent" or "SetVisibility"

Hi all,

I’m having some trouble with WIdgets management.
I want to press a key (in my case TAB) to open and close the UI (to est I just put a black square).
I’m doing it with C++ code and not with the blueprint.
When I first try to open it pressing TAB the widget appear and my black screen shows. But when I try to clause it pressing TAB again the black square remains there.
I tried first to use “remove from parent” and now I’m trying to set its visibility as false, but nothing changed, the Black square remains.
Here the screen of the code involved in the open and close action.
https://prnt.sc/13jymyh
Thank you in advance.

Try EVisiblity instead of ESlateVisibility

From the code you have posted:

  1. InventoryScreen is a local variable, that means it doesn’t have your created inventory next time you call the function

  2. You are creating another widget every time you call the function, assigning it to InventoryScreen and then hiding the new widget whereas the old one still in the background with lost reference.

Make InventoryWidget to be a member variable, so it persists a reference to the created widget and before creating the new widget, check if old one exists and create it only if it doesn’t exist or maybe move the creation it somewhere else.

If you want the widget to be always created and only hidden, I would use something like this (mockup code, you need to adapt it to your character by e.g. adding class scope to function names)

void Init()
{
	// Inventory widget is declared somewhere else
	InventoryWidget = CreateWidget(...);
	if(IsValid(InventoryWidget))
	{
		InventoryWidget->AddToViewport(0);
		InventoryWidget->SetVisibility(ESlateVisibility::Collapsed);
	}
}

void ToggleInventory()
{
	if (IsValid(InventoryWidget))
	{
		InventoryWidget->SetVisibility(InventoryWidget->IsVisible() ? ESlateVisibility::Collapsed : ESlateVisibility::SelfHitTestInvisible);
	}
}