Search code examples
c++unreal-engine4

How to send variable to widget from c++?


From code I want to assecc widget and and send string variable to it. But with my code I see only default value for it. Whet I set value in widget without code - it works.

Call method from another class:

  UChangeDialogBottomText* changeDialogBottomText = CreateWidget<UChangeDialogBottomText>(
    GetWorld()->GetFirstPlayerController(), UChangeDialogBottomText::StaticClass());
  if (changeDialogBottomText)
  {
    changeDialogBottomText->UpdateDialogBotton();
  }

.h

UCLASS()
class HOME_API UChangeDialogBottomText : public UUserWidget
{
  GENERATED_BODY()
  
public:
  UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (BindWidget)) FString st_Name_Key;

  UFUNCTION()
  void UpdateDialogBotton();
};

.cpp

void UChangeDialogBottomText::UpdateDialogBotton()
{
  st_Name_Key = "core";
}

enter image description here

enter image description here


Solution

  • The Event Construct pin the in the blueprint is only called once when the widget is created, not every time a variable changes. Therefore, if you want the UpdateDialogBotton method to change the text of the widget, then you have to call the SetText method in there. However, you will also need a reference to the text block widget in C++. Right now, you have a reference to it in blueprints. There are many ways to go about this, but the easiest way would be to make a new property in your header file like so,

    class UTextBlock; // <-- new line
    
    UCLASS()
    class HOME_API UChangeDialogBottomText : public UUserWidget
    {
      GENERATED_BODY()
      
    public:
      UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (BindWidget)) // <-- new line
      UTextBlock* name_Text_Block; // <-- new line
    
      UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (BindWidget)) 
      FString st_Name_Key;
    
      UFUNCTION()
      void UpdateDialogBotton();
    };
    

    And then in that event construct method in the blueprint, assign the name_Text_Block C++ variable to the Name blueprint variable. After doing that, you can change the text of the widget through the UpdateDialogBotton method like so,

    void UChangeDialogBottomText::UpdateDialogBotton()
    {
      st_Name_Key = "core";
      if (name_Text_Block) {
        name_Text_Block->SetText(FText::FromString(st_Name_Key));
      }
    }