среда, 13 октября 2021 г.

How to get widget size in Unreal Engine

The problem is absurd. You can't just get a size of widget before it will tick for a first time. I've met this problem when was writing a custom grid component. The component holds a set of widgets and should align them in a grid with cols count evaluating dynamically, depending on a size that widget takes on a parent widget at the moment of creation. And thats the problem.

As long as I am using dynamic ancors instead of fixed canvas slot size, the desired size of a widget can't be calculated.

If  layout was calculated you can accsess to last cached geometry. This is true for widgets that was added a frame before and have ticked once:

    MyWidget->GetCachedGeometry()

If you set widet size explicitly by using a canvas panel slot, you can get desired size by calling 

    auto Size = Cast<UCanvasSlot>(MyWidget->GetSlot())->Size;

or just call 

    auto Size = MyWidget->GetDesiredSize();

if widget was designed with SizeBox or some other widget that have a explicit fixed size property, wrapped around.

In more complicated cases you need to call 

    ForceLayoutPrepass(); 

to force desired size to be calculated.

You can read a great article that covers all that things here, if you not sure about what we are talking:

https://dawnarc.com/2018/12/ue4slate-and-native-umgc-notes/

Ok, nothing of that works for me

If nothing of that stuff works for you and you continue to get zeroes, there is last trick that you can try to do. The LayoutUtilites module goes to help. The trick is to walk upward in widget hierarchy by iterating through parents until you won't get widget with non-zeroed CachedGeometry and then use the geometry to calculate your newly-created widget that haven't been cached yet:


Be careful! This solution doesn't taking into account clipping rect, that could be used when widget is painted on a screen in a regular way.

1 комментарий: