🗒️
UE5 Widgetで文字幅を取得する(Slate)
Editor拡張で独自Windowを実装する時のメモ
SListView
でリストを表示する時に、その列に最大文字幅に合わせて、列ごとの幅を調整することになった
方法
フォントメジャーから横幅を取得し、そのままHeaderRowにFixedWidth()
で適応する
FSlateFontInfo
から取得が可能
// フォントメジャーを取得
TSharedRef<FSlateFontMeasure> FontMeasure =
FSlateApplication::Get().GetRenderer()->GetFontMeasureService();
FSlateFontInfo FontInfo = FAppStyle::Get().GetFontStyle("NormalText");
// Text: 表示する文字列
// TextSize: 実際のサイズ
FVector2D TextSize = FontMeasure->Measure(Text, FontInfo);
// 表示する予定の文字列を用意しておく
TArray<FString> ThisColumnsList = ItemsSource.get("ColumnId")
TSharedRef<FSlateFontMeasure> FontMeasure =
FSlateApplication::Get().GetRenderer()->GetFontMeasureService();
FSlateFontInfo FontInfo = FAppStyle::Get().GetFontStyle("NormalText");
// 縦列で最大を取得する
for (const FString ColumnName : *ThisColumnsList)
{
float MaxWidth = 100.f; // デフォルト値 (最小値)
FVector2D TextSize = FontMeasure->Measure(Text, FontInfo);
if (TextSize.X > MaxWidth)
{
MaxWidth = TextSize.X;
}
// 余白をプラス
MaxWidth += 42.f;
}
// 適応する
~~~
HeaderRow = SNew(SHeaderRow);
HeaderRow->AddColumn(
SHeaderRow::Column(FName(*Column))
.FixedWidth(MaxWidth)
)
~~~
数値はHeaderRow
に指定し、ItemはSMultiColumnTableRow
を使うことでItemも自動で調整される
割と正確に設定されるので便利
Discussion