How to create c++ widget

From IML Wiki
Jump to: navigation, search
  • Create child c++ class of UserWidget c++ class.
  • Create child blueprint class of created before c++ class.
  • Declare button uproperty
UPROPERTY(meta = (BindWidget))
class UButton* StartGame;
  • Create button with the same name as uproperty in the derived blueprint class.
  • Add virtual "UUserWidget::Initialize" function with "Super::Initialize();" function inside.
  • Add "Components/Button.h" header file.
  • Add some "void StartButtonClicked();" function will be delegated with our button OnClickedEvent. Signatures of this function must be the same that in called event!.
  • Create DynamicDelegate in the "UUserWidget::Initialize" function.


.h file

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "MyUserWidget.generated.h"

/**
 * 
 */
UCLASS()
class MYPROJECT_API UMyUserWidget : public UUserWidget
{
	GENERATED_BODY()

		virtual bool Initialize();

		UPROPERTY(meta = (BindWidget))
			class UButton* StartGame;
	
		UFUNCTION()
			void StartButtonClicked();
};

.cpp file

#include "MyUserWidget.h"
#include "Components/Button.h"

bool UMyUserWidget::Initialize()
{
	Super::Initialize();

	StartGame->OnClicked.AddDynamic(this, &UMyUserWidget::StartButtonClicked);

	return true;
}

void UMyUserWidget::StartButtonClicked()
{
	UE_LOG(LogTemp, Warning, TEXT("Our button is working!"));
}