UEC++ creates and binds Widget controls

UEC++ creates and binds Widget controls

introduction

I heard before that UEC++writing Widgetcontrols is a thankless task, and then I did some research and found that it is indeed the case. In UserWidgetthe blueprint, you only need to Imagedrag the control into the built-in CanvasPanelcontrol, but using code requires writing a lot of things, and it is only a basic tree structure. Therefore, it is highly not recommended to use UEC++write Widgetcontrols.

Attach the original link here (https://blog.csdn.net/weixin_43723303/article/details/126512815), it’s not easy to type by hand...

Here is the code:

CustomWidget.h

UClass()
class MYPROJECY2_API UCustomWidget : public UUserWidget
{
    GENERATED_BODY()

public:
    virtual void InitializeNativeClassData() override;
}

CustomWidget.cpp

#include "CustomWidget.h"
#include "Blueprint/WidgetTree.h"
#include "Components/CanvasPanel.h"
#include "GeneratedCodeHelpers.h"
#include "Components/PanelSlot.h"
#include "Components/CanvasPanelSlot.h"
#include "Components/Image.h"

void UCustomWidget::InitializeNativeClassData()
{
    // 新建 WidgetTree
    WidgetTree = NewObject<UWidgetTree>(this, UWidgetTree::StaticClass(), TEXT("WidgetTree"));
    
    // 新建 CanvasPanel 并绑定 Slot
    auto CanvasPanel = NewObject<UCanvasPanel>(WidgetTree, TEXT("CanvasPanel"));
    auto& PanelSlot = (*(AccessPrivateProperty<TArray<UPanelSlot*>>((CanvasPanel), UPanelWidget::__PPO__Slots())));
    PanelSlot = TArray<UPanelSlot*>();
    PanelSlot.Reserve(2);
    
    // 新建 Image 并绑定 Slot,并挂载到 CanvasPanel
    auto CanvasPanelSlot = NewObject<UCanvasPanelSlot>(CanvasPanel, TEXT("CanvasPanelSlot"));
    CanvasPanelSlot->Parent = CanvasPanel;
    auto Image = NewObject<UImage>(WidgetTree, TEXT("Image"));
    Image->Slot = CanvasPanelSlot;
    CanvasPanelSlot->Content = Image;
    PanelSlot.Add(CanvasPanelSlot);
    
    // 将 CanvasPanel 绑定到 WidgetTree
    WidgetTree->RootWidget = CanvasPanel;
    
    // 将 WidgetTree 绑定到 Class
    TArray<UWidgetAnimation*> WidgetAnimation;
    TArray<FDelegateRuntimeBinding> RuntimeBinding;
    UWidgetBlueprintGeneratedClass::InitializeWidgetStatic(this, GetClass(), WidgetTree, WidgetAnimation, RuntimeBinding);
}

Guess you like

Origin blog.csdn.net/weixin_43723303/article/details/126512815