2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[UE5] List ViewのViewmodel Extension

Posted at

Unreal Engineの複数のWidgetにViewmodel Extensionという項目が追加されており、有用そうだったので共有します。
主にList ViewのViewmodel Extensionについて解説します。

Viewmodel Extenstion

概要

List Viewやその他のPanel Widgetにある項目で、これを有効にすることでList ViewのItemと、Entryが持つViewmodelをバインドできる。

vmextension1.png

これが設定されているとList ItemのObject型は指定したViewmodel型になるため、List Item用のObject型を新しく定義する必要がなくなる。また、UListView::SetListItemsにViewmodelを渡すことで、それがEntryのViewmodelに渡される。

List ViewはItemとEntryという別のリスト要素概念を持つ。リストはItem (データ) の要素に基づいて形成されるが、Entry (表示物) は表示領域を満たす形で生成される。

Viewmodel Extensionを使ったList Viewの実装方法

  1. List View widgetを用意
    • List View widgetを任意のWBPに配置する
  2. List Viewの子widgetとしてEntry widgetを用意
    • UUserWidgetを継承したWBPを作成し、ClassSettings/InterfacesからUserObjectListEntryのインターフェースを実装する
      vmextension3.png
  3. Entry widgetにViewmodelを持たせる
    • ItemとしてList Viewに渡すためのViewmodelを定義し、Entry widgetのViewmodelsに追加する
  4. List ViewのList Entriesでプロパティを設定する
    • Viewmodel Extensionを有効にして、EntryWidgetClassおよびEntryViewmodelをセットする
      vmextension2.png
  5. Listに対してUListView::SetListItemsによってItemをセットする
    • View Bindingを使ってUListView::SetListItemsに対してView ModelのArrayを渡す
      vmextension5.png

Entry ViewmodelとSetListItemsで渡しているObject型が不一致の時にはエラーが表示される。

View Bindingの活用

View Bindingを活用することでWBPのGraphの記述を減らすのは重要なことで、Epic GamesのLearning用MVVMのサンプルプロジェクトでViewmodelの活用テクニックが見られます。Viewmodelで階層構造を持ってそれを受け渡したり、Conversion Functionをうまく使うことで、WBPのGraphの記述はかなり少なくなってます。

例えばWBP_Categoryを見てみると、下記のようなことが行われてます。

  • UIナビゲーションによって選択されたSelectedCategoryをViewmodel経由で渡してる
  • WBP_Category::VMPopulateSlots(ItemVMArray)に対して、CF_GetCategorySlots(ItemVMArray)を介して要素をMaxCapacityに合わせて成形したうえで、Widget生成関数に渡してる

UnrealEditor_bEpvl4VYKR.png

CFはConversion Functionの略で、Conversion関数を利用することでView Bindingだけで完結するような実装がされています。Conversion関数をうまく使えばほとんどWBPのGraphの記述をなくせそうですね。

Conversion関数

ついでにConversion関数についても調べてみました。下記の二点が満たされていればView BindingのConversion関数として表示されます。

  • Pure かつ Const
  • 関数が同一WBP内の定義か、Function Libraryに定義されている

UnrealEditor_aWWYFjMABJ.png

Viewmodelの関数内にConversion関数用意できたら便利そうだなと思って、使いたかったのですがそれはできませんでした。

今回の記事は以上です。
View Bindingは便利なので活用していきたいですね。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?