Download

How to initialize custom widgets

Hi,
I’d like to create a custom widget that can be initialized based on some game state.
So I wrote the following:

weapon_vbox.h


#pragma once

#include "Blueprint/UserWidget.h"
#include "Components/VerticalBox.h"

#include "weapon_vbox.generated.h"

UCLASS(BlueprintType)
class MYGAME_API Uweapon_vbox : public UVerticalBox
{
	GENERATED_BODY()

protected:
	void OnWidgetRebuilt();
};

weapon_vbox.cpp


#include "MyGame.h"

#include "weapon_vbox.h"

#include "Components/TextBlock.h"

void Uweapon_vbox::OnWidgetRebuilt()
{
	Super::OnWidgetRebuilt();
	UTextBlock *tester_text = CreateWidget<UTextBlock>(GetWorld(), UTextBlock::StaticClass());
	
	tester_text->SetText(FText::FromString(FString(TEXT("rock on"))));
	this->AddChild(tester_text);
}

Unfortunately as soon as I try to use this widget in a WidgetBlueprint the editor crashes.

I guess I didn’t put the initialization in the right place? And/or didn’t add the child node correctly?

So I’d like to initialize my widget with data that is not available at design time. How should I do that?

Thanks.

UE 4.7.1

CreateWidget can only be called for UUserWidget-derived classes, not UWidget-derived components.
I’m afraid I don’t know what the process is for constructing UWidgets dynamically in code - I’ve never tried to do it nor have I seen anything related to it.

Try this wiki you may find something to use

Thanks for your answers!

So if I understand correctly a “UUserWidget-derived class” is what I get when I do “Add New -> User Interface -> Widget Blueprint”?
And adding elements to UPanelWidgets is only possible at design time?

Thanks.

Solved

OK, looks like I can use ConstructObject() to create components.
Here’s a working example:


UTextBlock *tester_text = ConstructObject<UTextBlock>(UTextBlock::StaticClass());
tester_text->SetText(FText::FromString(TEXT("Tester Button")));
UButton *tester_button = ConstructObject<UButton>(UButton::StaticClass());
tester_button->AddChild(tester_text);
panel->AddChild(tester_button); // panel is a vertical box instance

I used this to modify a newly created instance of UUserWidget which has a vertical box (panel).

Cheers.

Cool, yeah I assumed it must be doable in C++, good to know this works.
By the way, ConstructObject has been deprecated as of 4.8; NewObject should be used instead.