C++ Adding Widget to WidgetTree doesn't update Hierarchy view in editor

Hey,

Sorry to revive the thread after so long, but I stumbled upon it when I was looking for an answer for the same issue so it might be worth finally answering it after I sorted it out for myself.

It was easier to understand after reading this article from Ben’s UI:

Basically I believe in order for the changes to be propagated correctly you will need to do several things:

  1. Get a reference to the Widget Blueprint as this is what you will need to be modifying:
const UWidgetBlueprintGeneratedClass* WidgetBlueprintGeneratedClass = Cast<UWidgetBlueprintGeneratedClass>(BaseWidget->GetClass());
const UPackage* Package = WidgetBlueprintGeneratedClass->GetPackage();
UWidgetBlueprint* MainAsset = Cast<UWidgetBlueprint>(Package->FindAssetInPackage());
  1. From that blueprint that you just got, find a reference to the widget you are trying to modify, in my case it was a CanvasPanel:
UCanvasPanel* FoundCanvasPanel = Cast<UCanvasPanel>(MainAsset->WidgetTree->FindWidget(BaseWidget->GetCanvasPanelName()));
  1. Construct the widget and assign it to the canvas or do whatever else you need to do with it:
FString WidgetName = FString::Printf(TEXT("Widget_%d"),i);
UUserWidget* PreviewUserWidget = MainAsset->WidgetTree->ConstructWidget<UUserWidget>(BaseWidget->WidgetToCreateClass, FName(WidgetName));

if(IsValid(PreviewUserWidget))
{
    UNodeWidget* NewWidget = Cast<UNodeWidget>(PreviewUserWidget);
    if(IsValid(NewWidget))
    {
        UPanelSlot* NewAddedSlot = FoundCanvasPanel->AddChild(NewWidget);
    }
  1. To propagate all of the changes so they do not get lost you will need to mark all of the assets that have been modified as “dirty” using Modify() and mark the blueprint as structurally modified:
FoundCanvasPanel->Modify();
MainAsset->Modify();

FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(MainAsset);

This code worked for me and it added my widgets to the Hierarchy and the screen.

I know this is a bit late :sweat_smile:, but I hope whoever finds this will have to struggle less than I did!