UE4 C++ widget

There are two ways to bind widgets in C++. One is to use meta = (BindWidget), and the other is to use GetWidgetFromName(TEXT("")). Both methods are acceptable.

1. meta = BindWidget method

    Note that in this binding method, the space name in UMG needs to be the same as the variable name declared in C++ Btn_StartUI

   

 2. GetWidgetFromName method

   

.h文件
UPROPERTY()
		UButton* Btn_Register;

.cpp文件
Btn_Register = Cast<UButton>(GetWidgetFromName(TEXT("Btn_Register")));

3. There are two ways to initialize the UI. The first is virtual void NativeConstruct() override; the second is bool Initialize() override;

.h文件
public:
	virtual void NativeConstruct() override;

	bool Initialize() override;

	UFUNCTION()
		void OnStartUIclickEvent();

	UFUNCTION()
		void LoginClickEvent();
.cpp文件
void UMyUserWidget::NativeConstruct()
{
	Super::NativeConstruct();

	Btn_Register = Cast<UButton>(GetWidgetFromName(TEXT("Btn_Register")));
	Btn_Register->OnClicked.AddDynamic(this,&UMyUserWidget::OnStartUIclickEvent);
}

bool UMyUserWidget::Initialize()
{
	if (!Super::Initialize())
	{
		return false;
	}
	Btn_StartUI->OnClicked.AddDynamic(this, &AMyGameMode::LoginClickEvent);
	return true;
}

4. The way to specify the blueprint UMG is TSubclassOf<UUserWidget> MySubClassOfWidget;

UPROPERTY(EditAnywhere,BlueprintReadWrite,Category = "Widget")
    TSubclassOf<UUserWidget> MySubClassOfWidget;

UUserWidget* TmpWidget = CreateWidget<UUserWidget>(GetWorld(),MySubClassOfWidget);

Select the UMG created in the blueprint

Guess you like

Origin blog.csdn.net/qq_43021038/article/details/125613409#comments_28606239