Setting texts in UMG from C++

I would like to know how I could set the text of a specific text block in an UMG widget from my C++ code. Specifically, I’d like to know how I could access the specific UTextBlock I want to modify in my code. If I were in Unity I could simply drag and drop the Text component in a field I made in my script and modify it from there. I am basically looking for an equivalent in UE4.

I am familiar with the blueprint way of doing this, but I would very much prefer to do this in code.


Assuming that you added a text block control in the BP editor. Given that, then you could do so in the following manner:

    UTextBlock* MyTextControl;

    // somewhere in the constructor
    MyTextControl = nullptr;

    // some location in code that is after the widgettree has been constructed
    const FName TextControlName = FName(TEXT("BPTextControl"));
    if (MyTextControl == nullptr)
        MyTextControl = (UTextBlock*)(WidgetTree->FindWidget(TextControlName));

    // some other location where you want to set the text
    if(MyTextControl != nullptr)
        MyTextControl->SetText(FText::FromString("Can you see your text?"));

Sorry for the late follow-up… I’m new here and this was the most relevant result for my search on how to do the same thing as the OP.

What is WidgetTree, and how do I get one from the UUserWidget* in my code?

Also, the compiler is saying that UTextBlock is known (and suggests that maybe I want STextBlock instead). Am I missing some include?

You should create TextBlock in Widgetblueprint and then, bind that TextBlock to your C++ Text Block, the name should be identical. Then you can set its properties in C++.
This is the SS of widget BP,
This is the SS of the header file where I declared TextBlock, see the name is same. Make sure you use meta in UPROPERTY.

This is the SS of the CPP file of the widget, make sure to use the event PReConstruct and not just simply Construct as PreConstruct will run while constructing the widget and not in Beginplay so you can see the changes in the editor instead of seeing the changes when you play.