Add UWidgets to a UserWidget using C++ in the Editor
How to programmatically build up a widget in the editor, while keeping the widget tree in sync.
Have you ever wanted to build the contents of a UUserWidget in the editor
using C++? For example imagine you want to create a gallery widget and you need
20 buttons with correct names. You could create them by hand, but it's slow and
error-prone.
The example below shows how to create widgets inside a User Widget blueprint,
from C++, and correctly update the widget tree so the new widgets can be
selected.
Huge thanks to @Sharundaar for sharing how to
do this in my Discord, and allowing me to share it
here.
Edit: It's worth mentioning that if you're trying to fill out a list, tree
or grid in the editor, to give designers an idea of how it will look, you
should consider using ListView.
Solution
First, we'll need to add "UMGEditor" and "UnrealEd" to your dependencies in
your Build.cs file.
We're doing something a little weird here, we're going to be adding some
editor-specific code to a non-editor class. In order to use the editor
functions, we need to add UnrealEd and UMGEditor to our list of modules in
MyProject.Build.cs, but only when building the editor.