Search code examples
c++unreal-engine4

How to change text in widget using c++


I have widget dialogBottom with element Text and I need to change it's text in c++. As I understand, if I use meta word, then I can write the name of widget and access it's variables by creating variables with the same name in code. But by some reason variable Name is always null

.h

UCLASS()
class HOME_API AAct_31 : public AActor
{
  GENERATED_BODY()

  UPROPERTY(BlueprintReadOnly, meta = (dialogBottom))
  class UTextBlock* Name = nullptr;

  virtual void Tick(float DeltaTime) override;
};

.cpp

void AAct_31::BeginPlay()
{
  Super::BeginPlay();
  
  if (Name)
  {
    char* t1 = "text1";
    FText t2 = FText::FromString(ANSI_TO_TCHAR(t1));
    Name->SetText(t2);
  }
}

enter image description here


Solution

  • As far as I know, if you want to change the text of a text block widget within a widget in C++, then you need to make a class of type UUserWidget and parent your widget blueprint with this class. And then in this class, you can call GetWidgetFromName to get specific widgets like so,

    // assuming that the native construct is overridden in the header file
    void UCustomWidget::NativeConstruct() {
        Super::NativeConstruct();
    
        // assuming that RandomTextBlock is defined in the header file and is of type UTextBlock*
        RandomTextBlock = (UTextBlock*)GetWidgetFromName(TEXT("Name_Of_TextBlock"));
        RandomTextBlock->SetText(FText::FromString("Random String"));
    }