UMG: How to set SLot property to a UWidget control?

Hi,

I’m creating a function in C++ that create UMG widgets at runtime. The problem is that I don’t understand how to add slot property to a widget.

Here I explain my example:



// I create a custom UCanvasPanel where I create an InitWithData funciton for add items

void USelectorBox::InitWithData(
	FTPArticle item){

	UCanvasPanelSlot* imageSlot = NewObject<UCanvasPanelSlot>(UCanvasPanelSlot::StaticClass());
	imageSlot->Parent = this;
	imageSlot->SetSize(FVector2D(200, 200));
	imageSlot->SetPosition(FVector2D(0, 0));

	UImage *backImage = NewObject<UImage>(UImage::StaticClass());
	backImage->Slot = imageSlot;
	backImage->SetColorAndOpacity(FLinearColor(1, 0, 0, 1));
	

	UCanvasPanelSlot* buttonSlot = NewObject<UCanvasPanelSlot>(UCanvasPanelSlot::StaticClass());
	buttonSlot->SetSize(FVector2D(180, 180));
	buttonSlot->SetPosition(FVector2D(10, 10));

	UButton *button = NewObject<UButton>(UButton::StaticClass());
	button->Slot = buttonSlot;

	FString ImagePath = item.Texture;
	UTexture2D* Texture = Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(ImagePath)));

	FSlateBrush itemBrush = UWidgetBlueprintLibrary::MakeBrushFromTexture(Texture);
	itemBrush.ImageSize.X = 180;
	itemBrush.ImageSize.Y = 180;
	itemBrush.DrawAs = ESlateBrushDrawType::Image;

	FButtonStyle style;
	style.SetNormal(itemBrush);
	style.SetHovered(itemBrush);
	style.SetPressed(itemBrush);

	button->WidgetStyle = style;
	
	AddChild(backImage);
	AddChild(button);

};


This code compile, but the slot property are not added to the widgets. Whats wrong in this code?
Thnaks

AddChild() returns the UPanelSlot* which you need to cast to UCanvasPanelSlot* and use that object instead of creating new one

Thaks a lot. Update the code like you suggest all work great!

Here the code updated:



UImage *backImage = NewObject<UImage>(UImage::StaticClass());
backImage->SetColorAndOpacity(FLinearColor(1, 0, 0, 1));
	
UCanvasPanelSlot* imageSlot = Cast<UCanvasPanelSlot>(AddChild(backImage));
imageSlot->Parent = this;
imageSlot->SetSize(FVector2D(200, 200));
imageSlot->SetPosition(FVector2D(0, 0));