Can't Cast Widget to CanvasPanelSlot (SlotAsCanvasSlot)

Hey all,

I’m making a custom UUserWidget, with a UBorder* InterfaceBackground as a member variable. I have the following lines of code:

		//Set up Canvas
		UCanvasPanelSlot* BackgroundAsCanvas = Cast<UCanvasPanelSlot>(InterfaceBackground->Slot);

		if (BackgroundAsCanvas)
		{
			BackgroundAsCanvas->SetAutoSize(true);
			BackgroundAsCanvas->SetDesiredPosition(WindowScreenPosition);
			UE_LOG(LogTemp, Error, TEXT("Interface Background slotted as canvas slot"));

		}
		else
		{
			UE_LOG(LogTemp, Error, TEXT("Interface Background could not be slotted as Canvas Slot!"));

		}

I’ve set it up correctly to a Blueprint Widget, but the Cast always fails due to BackgroundAsCanvas being invalid, getting the second error message.

Other ways I’ve tried is calling the UWidgetLayoutLibrary::SlotAsCanvasSlot, but that didn’t work either. I’ve also tried passing through the UUserWidget instead, but that fails as well.

The intent is that I can add this widget to the viewport without having it take up the entire screen, only the necessary amount.

I appreciate any advice.

1 Like

You are doing the cast in NativeConstruct()? I don’t think you can do it in the normal Constructor().

Here is a random snippet from our code casting something to slot.

//
// in the HUDWidget .h file
//

      UScaleBox* _mouseIcon_Crosshair = nullptr;
      UCanvasPanelSlot* _canvasPanelSlot_Crosshair = nullptr;

//
// in the HUDWidget .cpp file called in NativeConstruct()
// get ref to crosshair then cast to panel slot
//

     _mouseIcon_Crosshair = (UScaleBox*)GetWidgetFromName(MOUSE_ICON_CROSSHAIR);
     _canvasPanelSlot_Crosshair = UWidgetLayoutLibrary::SlotAsCanvasSlot(_mouseIcon_Crosshair);

1 Like

Its called in NativeConstruct?

Tried adding get widget from name. I’m not too familiar with the function, but I feel I’ve already accomplished that by adding BindWidget in UPROPERTY and adding a Border widget with the same name.

So no luck on that end. Thank you though.

Edit:
What’s strange about this is that, even if I do this in BP, I get an error that it accesses none when calling Slot As Canvas Slot. Although when it was done with a Widget BP that inherited from UUser Widget, it wasn’t a problem.