I am trying to create a UMG button (UButton) inside a verticalBox from C++ and make it appear inside the canvas of the UMG Widget I created as BluePrint.
I have googled up and down and can’t find a single working example,
neither for creating a UMG built-in type in C++
nor for displaying the created widget in the world.
Thanks for replying.
I am not trying to extend UUserWidget. I want to instantiate from C++ instances of the the existing UE4 UButton and UVerticalBox classes and make them show on my Widget (extended from UUserWidget) which is already attached to a view-port.
CreateWidget does not work with UButton.
I believe it’s still the same thing. You just need to use UUserWidget instead of YourCustomWidget. Buttons are not widgets on their own, they are components. So you need to create a widget first and then add buttons, verticalBoxes or whatever else to them. You can also check out this tutorial by Rama: A new, community-hosted Unreal Engine Wiki - Announcements - Epic Developer Community Forums
Rama is not doing it from C++, and if Buttons are components would you be kind enough to show me how to create a button from C++ and display it on my UUserWidget because I don’t have a clue.
you can create a widget in code with the global namespace “CreateWidget” call.
I do not know, if CreateWidget works with a native UButton, but you could also workaround this, by creating a UUserwidget
out of a widget-blueprint which has a nested UButton in it, and adding this widget to your parent.
I was having trouble figuring out how to do this in my widget I inherited from UUserWidget. Eventually figured out I needed to do a few casts, like casting GetRootWidget to a panel widget so I could add a child, and casting the result of that to a UCanvasPanelSlot instead of a normal UPanelSlot so I could set the position and scale information.
Here’s a code snipped in hopes that it helps someone…
// create image and set its position
UImage* image = WidgetTree->ConstructWidget<UImage>(UImage::StaticClass());
image->SetBrushFromTexture(IndicatorTexture);
image->SetColorAndOpacity(FLinearColor(0, 0, 0, 0));
// add it to child of root
UPanelWidget* root = Cast<UPanelWidget>(GetRootWidget());
UPanelSlot* slot = root->AddChild(image);
UCanvasPanelSlot* canvasSlot = Cast<UCanvasPanelSlot>(slot);
// set position and stuff
canvasSlot->SetAnchors(FAnchors(0.5f, 0.5f));
canvasSlot->SetAlignment(FVector2D(0.5f, 0.5f));
canvasSlot->SetOffsets(FMargin(0, 0, IndicatorSize, IndicatorSize));
Hey ThisGuy5234, that not solving the problem because ButtonTemplateWidget variable must be assigned an actual Widget Blueprint in the editor. The main concern is how to do it without a single interference from Widget Blueprint?
Hey this works well, thanks for the info. However, I have a question: I would like to alter the image (size , position etc.) in the blueprint editor after creating it in c++. Do I have to make the variables uproperties or why is this not working?