Game Dev/Unreal C++ : Dev Log
[언리얼] 동적으로 위젯 생성하기
GoldGiver
2023. 4. 26. 18:24
동적으로 위젯 생성하기
핵심 :
1. UUserWidget 은 CreateWidget, UWidget 은 ConstructWidget 을 사용해 위젯을 생성하자.
2. 생성 후, 그냥 WidgetTree 에 붙이기만 하면 된다.
3. AddChild 같은 함수로 부모자식 관계를 설정할 수 있다!
이전 글에서 동적으로 액터 컴포넌트를 만드는 방법을 기록한 적이 있는데, 이번에는 위젯을 동적으로 만드는 법을 알아보자. 코드는 사실 매우 간단하다 😄
원하는 위젯 클래스를 UUserWidget 으로부터 상속받아 만들었다고 하자. 그럼 아래와 같은 식으로 쓰면 된다 :
// UTextBlock 을 동적으로 생성하여 WidgetTree 에 붙인다
UTextBlock* textBlock = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass());
textBlock->SetText(FText::FromString(str));
// _verticalBox 아래에 UTextBlock 들 붙여주기 (ScaleBox 와 함께)
UScaleBox* scaleBox = WidgetTree->ConstructWidget<UScaleBox>(UScaleBox::StaticClass());
scaleBox->AddChild(textBlock);
_verticalBox->AddChild(scaleBox);
// VerticalBox 아래 슬롯들 채우기 레이아웃 설정
for (auto& slot : _verticalBox->GetSlots())
{
UVerticalBoxSlot* vSlot = Cast<UVerticalBoxSlot>(slot);
vSlot->SetSize(FSlateChildSize(ESlateSizeRule::Fill));
}
위에서는 UTextBlock 을 동적으로 만들어 WidgetTree 에 붙여주고 있다.
UScaleBox 를 만들어 UTextBlock 을 붙이고, 다시 이걸 UVerticalBox 아래로 넣은 다음... 해당 ScaleBox 를 UVerticalBoxSlot 으로 캐스팅해 채우기 설정을 변경해 주고 있다.
뭐... 더 설명할 건 거의 없다 😅
public:
/** The widget tree contained inside this user widget initialized by the blueprint */
UPROPERTY(Transient, DuplicateTransient, TextExportTransient)
UWidgetTree* WidgetTree;
참고로, WidgetTree 는 UUserWidget 에 선언되어 있다.
마지막으로... UWidget 을 상속받은 위젯은 ConstructWidget 을 사용하고, UUserWidget 을 상속받은 위젯의 경우 CreateWidget 을 사용한다!
참고 : 언리얼 공식 문서