# C++で作成したウィジェットが描画されない

**URL:** <https://forums.unrealengine.com/t/c/2054455>\
**Category:** 日本語 (Japanese)\
**Tags:** c-c, c-class-wizard, c-and-bluepri, c-custommeshcomponen, c-and-blueprint, c-error, c-class, c-custom-shape, c-programming, c-cone-shape, unreal-engine, CPP\
**Created:** [October 5, 2024, 2:22pm UTC](https://forums.unrealengine.com/t/c/2054455 "2024-10-05T14:22:17Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![T\_Sumisaki](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@T\_Sumisaki](https://forums.unrealengine.com/u/T_Sumisaki)\
**Post date:** [October 6, 2024, 6:43pm UTC](https://forums.unrealengine.com/t/c/2054455/2 "2024-10-06T18:43:47Z")

</div>

InitializeからNativeConstructまでの間にSlateのポインタが参照されてしまうので、NativeConstructのタイミングでWidgetTreeのRootWidgetを書き換えるのでは遅い、という理解です

WidgetReflectorで参照したところ、NativeConstructで記述した場合は、RootWidgetが見つからなかった場合のためのSSpacerが挿入されていました （ `UUserWidget::RebuildWidget` を参照のこと）

`UUserWidget::Initialize()` をオーバーライドし、そこでRootWidget（CanvasPanel）の追加をしてみてください  
その他の要素の設定はNativeConstructでOKです

```cpp

bool UMyUserWidget::Initialize()
{
    bool Result = Super::Initialize();

    if (!HasAnyFlags(RF_ClassDefaultObject))
    {
        RootCanvas = WidgetTree->ConstructWidget<UCanvasPanel>();
        WidgetTree->RootWidget = RootCanvas;
    }

    return Result;
}

void UMyUserWiget::NativeConstruct()
{
    // ...
}

```

参考：

> [@How to construct UMG widget in C++?](https://forums.unrealengine.com/t/how-to-construct-umg-widget-in-c/384615):
>
> I am trying to construct UMG widget in C++ and create simple button inside of it: void UMyUserWidget::NativeConstruct() { Super::NativeConstruct(); auto MyCanvas = WidgetTree-\>ConstructWidget\<UCanvasPanel\>(UCanvasPanel::StaticClass()); auto MyButton = NewObject\<UButton\>(this); MyCanvas-\>AddChildToCanvas(MyButton); WidgetTree-\>Modify(); WidgetTree-\>RootWidget = MyCanvas; } After adding this widget to viewport, this method is called, but i dont see any button on the screen.

---

_[View the full topic](https://forums.unrealengine.com/t/c/2054455)._
