C++ widget(小白临时记录)

 ue5的userwidge中的构造函数写法:需要在ue5的编辑器中创建c++类的userwidget类

处理图片类型需要使用UE提供的ImageWrapper模块,首先在project.Build.cs中加入ImageWrapper模块。

#include "ImageWrapperHelper.h"
//include后UpdateResource();才能用
Texture2D->UpdateResource();
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

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

public:
	
    //构造函数
	UMyUserWidget(const FObjectInitializer& ObjectInitializer);
		
	//创建蓝图类,在编辑器中指认蓝图类对象
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
	TSoftClassPtr<UUserWidget> BP_WidgetClass;
	
	UFUNCTION(BlueprintCallable)
	void loaduserwidget();

	void OnButton0Clicked();
};

用路径查找蓝图类进行软引用



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


UMyUserWidget::UMyUserWidget(const FObjectInitializer& ObjectInitializer)
	:Super(ObjectInitializer)
{
	
}
void UMyUserWidget::loaduserwidget()
{
	//通过路径的方式对蓝图类做软引用
    FSoftClassPath softclass(TEXT("WidgetBlueprint'/Game/BP_MyWidget.BP_MyWidget_C'"));
	UClass* widgetclass = softclass.TryLoadClass<UUserWidget>();
	BP_WidgetClass = widgetclass;
	
	if (BP_WidgetClass.IsValid())
	{
		BP_WidgetClass.LoadSynchronous();

		// 创建正确的用户界面类实例
		UUserWidget* BP_WidgetInstance = CreateWidget<UUserWidget>(GetWorld(), BP_WidgetClass.Get());
		if (BP_WidgetInstance)
		{
			UButton* buttonBP = Cast<UButton>(BP_WidgetInstance->GetWidgetFromName(TEXT("Button01")));
			
			buttonBP->OnClicked.AddDynamic(this,&UMyUserWidget::BeButtonClicked);
		}
	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Green, TEXT("Invalid BP_WidgetClass!"));
	}
}

void UMyUserWidget::BeButtonClicked()
{
	GEngine->AddOnScreenDebugMessage(-1,0.5f,FColor::Red,TEXT("this ok"));
}

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

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

/**
 * 
 */
UCLASS()
class WIDGETTEST001_API UMyUserWidget01 : public UUserWidget
{
	GENERATED_BODY()

protected:
	
	UPROPERTY(BlueprintReadWrite,meta = (bindwidget))
	class UTextBlock* TextLabel;

	UPROPERTY(BlueprintReadWrite,meta = (bindwidget))
	class UButton* testBtn;

	virtual void NativeConstruct() override;

	UFUNCTION()
	void testBtnOnClicked();

	
};
// Fill out your copyright notice in the Description page of Project Settings.


#include "MyUserWidget01.h"

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

void UMyUserWidget01::NativeConstruct()
{
	if (testBtn)
	{
		testBtn->OnClicked.AddDynamic(this,&UMyUserWidget01::testBtnOnClicked);
	}
}

void UMyUserWidget01::testBtnOnClicked()
{
	TextLabel->SetText(FText::AsNumber(17));
}
// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "widgetTest001GameModeBase.generated.h"

/**
 * 
 */
UCLASS()
class WIDGETTEST001_API AwidgetTest001GameModeBase : public AGameModeBase
{
	GENERATED_BODY()

protected:
	
	UPROPERTY(EditAnywhere,Category = "Class Types")
	//定义一个变量,该变量持有从 UUserWidget 类派生的类的引用,TSubclassOf虚幻中的一个模版类,用于表示一个类的引用。
	TSubclassOf<UUserWidget> widgetclass;

	UPROPERTY(VisibleInstanceOnly,Category = "Runtime")
	//创建一个MyUserWidget01类型的变量
	class UMyUserWidget01* MyUserWidget01;

	virtual void BeginPlay() override;


};
// Copyright Epic Games, Inc. All Rights Reserved.


#include "widgetTest001GameModeBase.h"
#include "MyUserWidget01.h"

#include "Blueprint/UserWidget.h"

void AwidgetTest001GameModeBase::BeginPlay()
{
	if (IsValid(widgetclass))
	{
		MyUserWidget01 =Cast<UMyUserWidget01> (CreateWidget(GetWorld(), widgetclass));
		if (MyUserWidget01 != nullptr)
		{
			MyUserWidget01->AddToViewport();
		}

	}
	
}	

ue4创建窗口

int AwidgetTest001GameModeBase::newwindow()
{
	
	
	TSharedPtr<SWindow> mianwin = SNew(SWindow).ClientSize(FVector2D(1280.f, 720.f))[SNew(SImage)];

	FSlateApplication::Get().AddWindow(mianwin.ToSharedRef());
	while (!GIsRequestingExit)
	{
		FSlateApplication::Get().Tick();
		FSlateApplication::Get().PumpMessages();
	}
	FSlateApplication::Shutdown();
	return 0;
	
	
}

补充经过测试的方法:如果只是将一个BP类的用户界面用代码的方式添加到视口是不用创建uuserwidget的c++类的,如果需要在代码中方法BP类的用户界面中的小部件就需要创建c++类的userwidget了,然后将BP类的类设置中的父类设置为userwidget,创建userwidget的方法可在编辑器中右键新建c++类中的所有类中搜索userwidget并创建,

static ConstructorHelpers::FClassFinder<UUserWidget> WidgetBPClass(TEXT("/Game/NewWidgetBlueprint.NewWidgetBlueprint_C"));只能放在构造函数中使用,否则运行会崩溃。

h
创建一个TSubclassOf<UUserWidget> WidgetClass;

cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "OpencvT/Public/MyOpenCVClass.h"

#if WITH_OPENCV
#include "PreOpenCVHeaders.h"
#include "opencv2/opencv.hpp"
#include "PostOpenCVHeaders.h"
#endif

#include "MyUserWidget.h"



// Sets default values
AMyOpenCVClass::AMyOpenCVClass()
{
	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
	
	static ConstructorHelpers::FClassFinder<UUserWidget> WidgetBPClass(TEXT("/Game/NewWidgetBlueprint.NewWidgetBlueprint_C"));
	if (WidgetBPClass.Succeeded())
	{
		WidgetClass = WidgetBPClass.Class;
	}
}

// Called when the game starts or when spawned
void AMyOpenCVClass::BeginPlay()
{
	Super::BeginPlay();
//	//cv::VideoCapture Capture("d:\\add.png");;
//	cv::Mat img = cv::imread("d:\\add.png");
//	if (!img.empty())
//	{
//		GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Purple, TEXT("open ok"));
//	}
//	else
//	{
//		GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, TEXT("Failed to open file"));
//	}
//
//	UTexture2D* Texture = nullptr;
//	
//	{
//		Texture = UTexture2D::CreateTransient(img.cols, img.rows);
//
//		if (!Texture)
//		{
//			return ;
//		}
//
//		Texture->NeverStream = true;
//		Texture->SRGB = 0;
//
//		if (img.channels() == 1)
//		{
//			Texture->CompressionSettings = TextureCompressionSettings::TC_Grayscale;
//		}
//
//		FTexture2DMipMap& Mip0 = Texture->GetPlatformData()->Mips[0];
//		void* TextureData = Mip0.BulkData.Lock(LOCK_READ_WRITE);
//
//		const int32 PixelStride = img.channels();
//		FMemory::Memcpy(TextureData, img.data, img.cols * img.rows * SIZE_T(PixelStride));
//
//		Mip0.BulkData.Unlock();
//
//		Texture->UpdateResource();
//	}

	// 加载MyUserWidget蓝图类

	UWorld* World = GetWorld();
	if (!World)
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("GetWorld() returned nullptr"));
		return;
	}

	
	if (WidgetClass)
	{
		UUserWidget* MyWidget = CreateWidget<UUserWidget>(GetWorld(), WidgetClass);
		if (MyWidget)
		{
			MyWidget->AddToViewport();
			GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Green, TEXT("Widget added to viewport"));
		}
		else
		{
			GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Failed to create widget instance"));
		}
	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("WidgetClass is not valid"));
	}
	
}

// Called every frame
void AMyOpenCVClass::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我救我自己

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值