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
kamrann
(kamrann)
July 18, 2015, 8:33am
2
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 UWidget s dynamically in code - I’ve never tried to do it nor have I seen anything related to it.
Bn_Green
(Bn_Green)
July 18, 2015, 5:09pm
3
Try this wiki you may find something to use
After over a year in maintenance mode, the official Unreal Engine Wiki is now permanently offline. These resources now live on a new community-run Unreal Engine Community Wiki — ue4community.wiki! You will be able to find content from the official...
Reading time: 1 mins 🕑
Likes: 8 ❤
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 UPanelWidget s 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.
kamrann
(kamrann)
July 19, 2015, 9:43pm
6
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.