Hi guys I will paste some code from my project,I’m using UE 5.3.2 and it works
// POIFullScreenWidget.h
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "Components/CanvasPanel.h"
#include "POIFullScreenWidget.generated.h"
/**
*
*/
UCLASS()
class AMAPLAYERS_API UPOIFullScreenWidget : public UUserWidget
{
GENERATED_BODY()
public:
UPOIFullScreenWidget(const FObjectInitializer& ObjectInitializer);
UCanvasPanel* CanvasPanel;
virtual void NativeOnInitialized() override;
};
// Fill out your copyright notice in the Description page of Project Settings.
#include "POIFullScreenWidget.h"
#include "Blueprint/WidgetTree.h"
#include "Components/CanvasPanelSlot.h"
UPOIFullScreenWidget::UPOIFullScreenWidget(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
}
// here we create a simple text
void UPOIFullScreenWidget::NativeOnInitialized()
{
Super::NativeOnInitialized();
CanvasPanel = WidgetTree->ConstructWidget<UCanvasPanel>(UCanvasPanel::StaticClass());
if (CanvasPanel)
{
auto TextBlock = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass());
TextBlock->SetText(FText::FromString("Hello World!"));
auto TextSlot = CanvasPanel->AddChildToCanvas(TextBlock);
TextSlot->SetAnchors(FAnchors(0, 0, 0, 0));
TextSlot->SetOffsets(FMargin(100, 100));
TextSlot->SetAlignment(FVector2d(0, 0.5));
TextSlot->SetAutoSize(true);
WidgetTree->RootWidget = CanvasPanel;
}
}