関連ブログ
- [UE4][UE5]開発環境の容量を少しでも減らす 2024.08.14UE
- [UE5] PushModel型のReplicationを使い、ネットワーク最適化を図る 2024.05.29UE
- [UE5]マテリアルでメッシュをスケールする方法 2024.01.17UE
CATEGORY
2019.10.23UE4UE/ C++
執筆バージョン: Unreal Engine 4.22 |
以前ご紹介した記事で独自の型の変数をコンボボックスから選択できるようにしました。
ですがこのデータテーブルの項目がある程度増えてくると目的の項目を探すのに非常に手間がかかってしまいます。
そこで今回は以前の記事で実装した機能を拡張し、以下の画像のような検索欄を追加したいと思います。
デフォルトのコンボボックスは、「Engine\Source\Runtime\Slate\Public\Widgets\Input\SComboBox.h」で定義されています。 SComboBoxはテンプレートで定義されており、配列の中身の型にしばられず様々なものを一覧表示してくれます。 前回使っていたものは文字列を一覧してくれる「STextComboBox」というものになります。 SComboBoxはボタンとそのボタンを押したときに新たにテキストを一覧するウィンドウの2部分で構成されています。 今回追加したい部分はこの「テキストを一覧するウィンドウ」の最上部となりますのでSComboBoxから改造する必要があります。
コンボボックスのコードに直接かくとエンジン改造になってしまい大事になるのでベースは「SComboBox.h」をコピペして新規のクラスを定義していきます。 前回作ったTestEdフォルダ以下に「CustomComboBox.h」を作成し以下のコードを記述します
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
#pragma once #include "CoreMinimal.h" #include "InputCoreTypes.h" #include "Layout/Margin.h" #include "Styling/SlateColor.h" #include "Widgets/SNullWidget.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Input/Events.h" #include "Input/Reply.h" #include "Widgets/SWidget.h" #include "Sound/SlateSound.h" #include "Styling/SlateTypes.h" #include "Styling/CoreStyle.h" #include "Framework/SlateDelegates.h" #include "Framework/Application/SlateApplication.h" #include "Widgets/Text/STextBlock.h" #include "Widgets/Layout/SBox.h" #include "Widgets/Input/SComboButton.h" #include "Widgets/Views/STableViewBase.h" #include "Framework/Views/TableViewTypeTraits.h" #include "Widgets/Views/STableRow.h" #include "Widgets/Views/SListView.h" #include "Widgets/Input/SComboBox.h" #include "Widgets/Input/SSearchBox.h" DECLARE_DELEGATE(FOnComboBoxOpening) /** * A combo box that shows arbitrary content. */ class SCustomComboBox : public SComboButton { public: /** Type of list used for showing menu options. */ typedef SListView& lt; TSharedPtr& gt; SComboListType; /** Delegate type used to generate widgets that represent Options */ typedef typename TSlateDelegates& lt; TSharedPtr& gt; ::FOnGenerateWidget FOnGenerateWidget; typedef typename TSlateDelegates& lt; TSharedPtr& gt; ::FOnSelectionChanged FOnSelectionChanged; TSharedPtr SearchBox; SLATE_BEGIN_ARGS(SCustomComboBox) : _Content() , _ComboBoxStyle(& FCoreStyle::Get().GetWidgetStyle& lt; FComboBoxStyle& gt; ("ComboBox")) , _ButtonStyle(nullptr) , _ItemStyle(& FCoreStyle::Get().GetWidgetStyle& lt; FTableRowStyle& gt; ("TableView.Row")) , _ContentPadding(FMargin(4.0, 2.0)) , _ForegroundColor(FCoreStyle::Get().GetSlateColor("InvertedForeground")) , _OptionsSource() , _OnSelectionChanged() , _OnGenerateWidget() , _InitiallySelectedItem(nullptr) , _Method() , _MaxListHeight(450.0f) , _HasDownArrow(true) , _EnableGamepadNavigationMode(false) , _IsFocusable(true) {} /** Slot for this button's content (optional) */ SLATE_DEFAULT_SLOT(FArguments, Content) SLATE_STYLE_ARGUMENT(FComboBoxStyle, ComboBoxStyle) /** The visual style of the button part of the combo box (overrides ComboBoxStyle) */ SLATE_STYLE_ARGUMENT(FButtonStyle, ButtonStyle) SLATE_STYLE_ARGUMENT(FTableRowStyle, ItemStyle) SLATE_ATTRIBUTE(FMargin, ContentPadding) SLATE_ATTRIBUTE(FSlateColor, ForegroundColor) SLATE_ARGUMENT(const TArray& lt; TSharedPtr& gt;*, OptionsSource) SLATE_EVENT(FOnSelectionChanged, OnSelectionChanged) SLATE_EVENT(FOnGenerateWidget, OnGenerateWidget) //SLATE_EVENT(FOnTextChanged, OnSearchTextChanged) /** Called when combo box is opened, before list is actually created */ SLATE_EVENT(FOnComboBoxOpening, OnComboBoxOpening) /** The custom scrollbar to use in the ListView */ SLATE_ARGUMENT(TSharedPtr, CustomScrollbar) /** The option that should be selected when the combo box is first created */ SLATE_ARGUMENT(TSharedPtr, InitiallySelectedItem) SLATE_ARGUMENT(TOptional, Method) /** The max height of the combo box menu */ SLATE_ARGUMENT(float, MaxListHeight) /** The sound to play when the button is pressed (overrides ComboBoxStyle) */ SLATE_ARGUMENT(TOptional, PressedSoundOverride) /** The sound to play when the selection changes (overrides ComboBoxStyle) */ SLATE_ARGUMENT(TOptional, SelectionChangeSoundOverride) /** * When false, the down arrow is not generated and it is up to the API consumer * to make their own visual hint that this is a drop down. */ SLATE_ARGUMENT(bool, HasDownArrow) /** * When false, directional keys will change the selection. When true, ComboBox * must be activated and will only capture arrow input while activated. */ SLATE_ARGUMENT(bool, EnableGamepadNavigationMode) /** When true, allows the combo box to receive keyboard focus */ SLATE_ARGUMENT(bool, IsFocusable) SLATE_END_ARGS() /** * Construct the widget from a declaration * * @param InArgs Declaration from which to construct the combo box */ void Construct(const FArguments& amp; InArgs) { check(InArgs._ComboBoxStyle); ItemStyle = InArgs._ItemStyle; // Work out which values we should use based on whether we were given an override, or should use the style's version const FComboButtonStyle& amp; OurComboButtonStyle = InArgs._ComboBoxStyle - > ComboButtonStyle; const FButtonStyle* const OurButtonStyle = InArgs._ButtonStyle ? InArgs._ButtonStyle : & OurComboButtonStyle.ButtonStyle; PressedSound = InArgs._PressedSoundOverride.Get(InArgs._ComboBoxStyle - > PressedSlateSound); SelectionChangeSound = InArgs._SelectionChangeSoundOverride.Get(InArgs._ComboBoxStyle - > SelectionChangeSlateSound); this - > OnComboBoxOpening = InArgs._OnComboBoxOpening; this - > OnSelectionChanged = InArgs._OnSelectionChanged; this - > OnGenerateWidget = InArgs._OnGenerateWidget; //this->OnSearchTextChanged = InArgs._OnSearchTextChanged; this - > EnableGamepadNavigationMode = InArgs._EnableGamepadNavigationMode; FilterdArray = new TArray & lt; TSharedPtr& gt; (); OptionsSource = InArgs._OptionsSource; CustomScrollbar = InArgs._CustomScrollbar; FilterdArray - > Reset(); for (int i = 0; i & lt; OptionsSource - > Num(); i++) { FilterdArray - > Add(OptionsSource - > GetData()[i]); } TSharedRef ComboBoxMenuContent = SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SAssignNew(SearchBox, SSearchBox) .OnTextChanged(this, & SCustomComboBox::OnSearchTextChanged) ] + SVerticalBox::Slot() .HAlign(HAlign_Left) [ SNew(SBox) .MaxDesiredHeight(InArgs._MaxListHeight) [ SAssignNew(this - > ComboListView, SComboListType) .ListItemsSource(FilterdArray) .OnGenerateRow(this, & SCustomComboBox::GenerateMenuItemRow) .OnSelectionChanged(this, & SCustomComboBox::OnSelectionChanged_Internal) .SelectionMode(ESelectionMode::Single) .ExternalScrollbar(InArgs._CustomScrollbar) ] ]; // Set up content TSharedPtr ButtonContent = InArgs._Content.Widget; if (InArgs._Content.Widget == SNullWidget::NullWidget) { SAssignNew(ButtonContent, STextBlock) .Text(NSLOCTEXT("SCustomComboBox", "ContentWarning", "No Content Provided")) .ColorAndOpacity(FLinearColor::Red); } SComboButton::Construct(SComboButton::FArguments() .ComboButtonStyle(& OurComboButtonStyle) .ButtonStyle(OurButtonStyle) .Method(InArgs._Method) .ButtonContent() [ ButtonContent.ToSharedRef() ] .MenuContent() [ ComboBoxMenuContent ] .HasDownArrow(InArgs._HasDownArrow) .ContentPadding(InArgs._ContentPadding) .ForegroundColor(InArgs._ForegroundColor) .OnMenuOpenChanged(this, & SCustomComboBox::OnMenuOpenChanged) .IsFocusable(InArgs._IsFocusable) ); SetMenuContentWidgetToFocus(ComboListView); // Need to establish the selected item at point of construction so its available for querying // NB: If you need a selection to fire use SetItemSelection rather than setting an IntiallySelectedItem SelectedItem = InArgs._InitiallySelectedItem; if (TListTypeTraits& lt; TSharedPtr & gt; ::IsPtrValid(SelectedItem)) { ComboListView - > Private_SetItemSelection(SelectedItem, true); ComboListView - > RequestScrollIntoView(SelectedItem, 0); } } void ClearSelection() { ComboListView - > ClearSelection(); } void SetSelectedItem(TSharedPtr InSelectedItem) { if (TListTypeTraits& lt; TSharedPtr & gt; ::IsPtrValid(InSelectedItem)) { ComboListView - > SetSelection(InSelectedItem); } else { ComboListView - > ClearSelection(); } } /** @return the item currently selected by the combo box. */ TSharedPtr GetSelectedItem() { return SelectedItem; } /** * Requests a list refresh after updating options * Call SetSelectedItem to update the selected item if required * @see SetSelectedItem */ void RefreshOptions() { ComboListView - > RequestListRefresh(); } protected: /** Handle key presses that SListView ignores */ virtual FReply OnHandleKeyPressed(FKey KeyPressed) { if (KeyPressed == EKeys::Enter || KeyPressed == EKeys::SpaceBar || KeyPressed == EKeys::Virtual_Accept) { TArray& lt; TSharedPtr& gt; SelectedItems = ComboListView - > GetSelectedItems(); if (SelectedItems.Num() & gt; 0) { ComboListView - > SetSelection(SelectedItems[0]); } return FReply::Handled(); } else if (KeyPressed == EKeys::Escape) { this - > SetIsOpen(false); return FReply::Handled(); } return FReply::Unhandled(); } FReply OnKeyDown(const FGeometry& amp; MyGeometry, const FKeyEvent& amp; InKeyEvent) override { const FKey KeyPressed = InKeyEvent.GetKey(); if (IsInteractable()) { if (EnableGamepadNavigationMode) { // The controller's bottom face button must be pressed once to begin manipulating the combobox's value. // Navigation away from the widget is prevented until the button has been pressed again or focus is lost. if (KeyPressed == EKeys::Enter || KeyPressed == EKeys::SpaceBar || KeyPressed == EKeys::Virtual_Accept) { if (bControllerInputCaptured == false) { // Begin capturing controller input and open the ListView bControllerInputCaptured = true; PlayPressedSound(); OnComboBoxOpening.ExecuteIfBound(); return SComboButton::OnButtonClicked(); } else { // Set selection to the selected item on the list and close bControllerInputCaptured = false; // Re-select first selected item, just in case it was selected by navigation previously TArray& lt; TSharedPtr& gt; SelectedItems = ComboListView - > GetSelectedItems(); if (SelectedItems.Num() & gt; 0) { OnSelectionChanged_Internal(SelectedItems[0], ESelectInfo::Direct); } // Set focus back to ComboBox FReply Reply = FReply::Handled(); Reply.SetUserFocus(this - > AsShared(), EFocusCause::SetDirectly); return Reply; } } else if (KeyPressed == EKeys::Escape || KeyPressed == EKeys::Virtual_Back || KeyPressed == EKeys::BackSpace) { OnMenuOpenChanged(false); } else { if (bControllerInputCaptured) { return FReply::Handled(); } } } else { if (KeyPressed == EKeys::Up || KeyPressed == EKeys::Gamepad_DPad_Up || KeyPressed == EKeys::Gamepad_LeftStick_Up) { const int32 SelectionIndex = OptionsSource - > Find(GetSelectedItem()); if (SelectionIndex& gt; = 1) { // Select an item on the prev row SetSelectedItem((*OptionsSource)[SelectionIndex - 1]); } return FReply::Handled(); } else if (KeyPressed == EKeys::Down || KeyPressed == EKeys::Gamepad_DPad_Down || KeyPressed == EKeys::Gamepad_LeftStick_Down) { const int32 SelectionIndex = OptionsSource - > Find(GetSelectedItem()); if (SelectionIndex& lt; OptionsSource - > Num() - 1) { // Select an item on the next row SetSelectedItem((*OptionsSource)[SelectionIndex + 1]); } return FReply::Handled(); } return SComboButton::OnKeyDown(MyGeometry, InKeyEvent); } } return SWidget::OnKeyDown(MyGeometry, InKeyEvent); } virtual bool SupportsKeyboardFocus() const override { return bIsFocusable; } virtual bool IsInteractable() const { return IsEnabled(); } private: /** Generate a row for the InItem in the combo box's list (passed in as OwnerTable). Do this by calling the user-specified OnGenerateWidget */ TSharedRef GenerateMenuItemRow(TSharedPtr InItem, const TSharedRef& amp; OwnerTable) { if (OnGenerateWidget.IsBound()) { return SNew(SComboRow & lt; TSharedPtr & gt;, OwnerTable) .Style(ItemStyle) [ OnGenerateWidget.Execute(InItem) ]; } else { return SNew(SComboRow & lt; TSharedPtr & gt;, OwnerTable) [ SNew(STextBlock).Text(NSLOCTEXT("SlateCore", "ComboBoxMissingOnGenerateWidgetMethod", "Please provide a .OnGenerateWidget() handler.")) ]; } } //** Called if the menu is closed void OnMenuOpenChanged(bool bOpen) { if (bOpen == false) { bControllerInputCaptured = false; if (TListTypeTraits& lt; TSharedPtr & gt; ::IsPtrValid(SelectedItem)) { // Ensure the ListView selection is set back to the last committed selection ComboListView - > SetSelection(SelectedItem, ESelectInfo::OnNavigation); ComboListView - > RequestScrollIntoView(SelectedItem, 0); //mboListView->get } // Set focus back to ComboBox for users focusing the ListView that just closed FSlateApplication::Get().ForEachUser([&](FSlateUser* User) { if (FSlateApplication::Get().HasUserFocusedDescendants(AsShared(), User - > GetUserIndex())) { FSlateApplication::Get().SetUserFocus(User - > GetUserIndex(), AsShared(), EFocusCause::SetDirectly); } }); } } /** Invoked when the selection in the list changes */ void OnSelectionChanged_Internal(TSharedPtr ProposedSelection, ESelectInfo::Type SelectInfo) { // Ensure that the proposed selection is different if (SelectInfo != ESelectInfo::OnNavigation) { // Ensure that the proposed selection is different from selected if (ProposedSelection != SelectedItem) { PlaySelectionChangeSound(); SelectedItem = ProposedSelection; OnSelectionChanged.ExecuteIfBound(ProposedSelection, SelectInfo); } // close combo even if user reselected item this - > SetIsOpen(false); } } /** Handle clicking on the content menu */ virtual FReply OnButtonClicked() override { // if user clicked to close the combo menu if (this - > IsOpen()) { // Re-select first selected item, just in case it was selected by navigation previously TArray& lt; TSharedPtr& gt; SelectedItems = ComboListView - > GetSelectedItems(); if (SelectedItems.Num() & gt; 0) { OnSelectionChanged_Internal(SelectedItems[0], ESelectInfo::Direct); } } else { PlayPressedSound(); OnComboBoxOpening.ExecuteIfBound(); } SearchBox - > SetText(FText::GetEmpty()); return SComboButton::OnButtonClicked(); } /** Play the pressed sound */ void PlayPressedSound() const { FSlateApplication::Get().PlaySound(PressedSound); } /** Play the selection changed sound */ void PlaySelectionChangeSound() const { FSlateApplication::Get().PlaySound(SelectionChangeSound); } void OnSearchTextChanged(const FText& amp; NewText) { FilterString = NewText.ToString(); FilterdArray - > Reset(); if (FilterString.IsEmpty()) { for (int i = 0; i & lt; OptionsSource - > Num(); i++) { FilterdArray - > Add(OptionsSource - > GetData()[i]); } } else { FilterdArray - > Add(OptionsSource - > GetData()[0]); for (int i = 1; i & lt; OptionsSource - > Num(); i++) { auto s = OptionsSource - > GetData()[i]; if (s - > Contains(FilterString) || s == SelectedItem) { FilterdArray - > AddUnique(s); } } } ComboListView - > RebuildList(); } FString FilterString; /** The Sound to play when the button is pressed */ FSlateSound PressedSound; /** The Sound to play when the selection is changed */ FSlateSound SelectionChangeSound; /** The item style to use. */ const FTableRowStyle* ItemStyle; TArray& lt; TSharedPtr& gt; *FilterdArray = nullptr; private: /** Delegate that is invoked when the selected item in the combo box changes */ FOnSelectionChanged OnSelectionChanged; /** The item currently selected in the combo box */ TSharedPtr SelectedItem; /** The ListView that we pop up; visualized the available options. */ TSharedPtr& lt; SComboListType& gt; ComboListView; /** The Scrollbar used in the ListView. */ TSharedPtr& lt; SScrollBar& gt; CustomScrollbar; /** Delegate to invoke before the combo box is opening. */ FOnComboBoxOpening OnComboBoxOpening; /** Delegate to invoke when we need to visualize an option as a widget. */ FOnGenerateWidget OnGenerateWidget; // Use activate button to toggle ListView when enabled bool EnableGamepadNavigationMode; // Holds a flag indicating whether a controller/keyboard is manipulating the combobox's value. // When true, navigation away from the widget is prevented until a new value has been accepted or canceled. bool bControllerInputCaptured; const TArray& lt; TSharedPtr& gt; *OptionsSource; }; |
ComboBox内で一覧するウィンドウを作っているのが、ComboBoxMenuContentをSNewしているあたりになります。 なのでここにSearchBoxを追加します。 SAssignNewとしておくことで、変数に格納しておいてあとでこのSearchBoxに対して操作ができるようになります。 SearchBoxの検索処理自体は自前で書く必要があるため、ここで一旦変数に格納しておきます。 そして検索処理と一覧する項目の変更はOnSearchTextChanged()で行っています。 これはSearchBoxのテキストが変更された瞬間に実行されるようになっており、検索欄に入力された文字列を含む要素のみ、配列に格納していきます。 配列の内容を更新し終わったら、ComboListView->RebuildList();によって一覧する項目の更新をします。
STextComboBoxはデフォルトではSComboBoxを生成して使用していますが、新たに作成した検索欄付きのSCustomComboBoxを使用するように修正します。 エンジン改造とならないようにベースはSTextComboBox .h/.cppをコピペして使います。新たに作るファイルはそれぞれCustomTextComboBox .h/.cppとします。 コードは以下のとおりです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
#pragma once #include "CoreMinimal.h" #include "Misc/Attribute.h" #include "Layout/Margin.h" #include "Styling/SlateColor.h" #include "Fonts/SlateFontInfo.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Widgets/SWidget.h" #include "Widgets/SCompoundWidget.h" #include "Styling/SlateTypes.h" #include "Styling/CoreStyle.h" #include "Framework/SlateDelegates.h" #include "CustomComboBox.h" /** * A combo box that shows text content. */ class TEST_API SCustomTextComboBox : public SCompoundWidget { public: DECLARE_DELEGATE_RetVal_OneParam(FString, FGetTextComboLabel, TSharedPtr); typedef TSlateDelegates& lt; TSharedPtr& gt; ::FOnSelectionChanged FOnTextSelectionChanged; SLATE_BEGIN_ARGS(SCustomTextComboBox) : _ComboBoxStyle(& FCoreStyle::Get().GetWidgetStyle& lt; FComboBoxStyle& gt; ("ComboBox")) , _ButtonStyle(nullptr) , _ColorAndOpacity(FSlateColor::UseForeground()) , _ContentPadding(FMargin(4.0, 2.0)) , _OnGetTextLabelForItem() {} SLATE_STYLE_ARGUMENT(FComboBoxStyle, ComboBoxStyle) /** The visual style of the button part of the combo box (overrides ComboBoxStyle) */ SLATE_STYLE_ARGUMENT(FButtonStyle, ButtonStyle) /** Selection of strings to pick from */ SLATE_ARGUMENT(TArray& lt; TSharedPtr& gt;*, OptionsSource) /** Text color and opacity */ SLATE_ATTRIBUTE(FSlateColor, ColorAndOpacity) /** Sets the font used to draw the text */ SLATE_ATTRIBUTE(FSlateFontInfo, Font) /** Visual padding of the button content for the combobox */ SLATE_ATTRIBUTE(FMargin, ContentPadding) /** Called when the text is chosen. */ SLATE_EVENT(FOnTextSelectionChanged, OnSelectionChanged) /** Called when the combo box is opened */ SLATE_EVENT(FOnComboBoxOpening, OnComboBoxOpening) /** Called when combo box needs to establish selected item */ SLATE_ARGUMENT(TSharedPtr, InitiallySelectedItem) /** [Optional] Called to get the label for the currently selected item */ SLATE_EVENT(FGetTextComboLabel, OnGetTextLabelForItem) SLATE_END_ARGS() void Construct(const FArguments& amp; InArgs); /** Called to create a widget for each string */ TSharedRef MakeItemWidget(TSharedPtr StringItem); void SetSelectedItem(TSharedPtr NewSelection); /** Returns the currently selected text string */ TSharedPtr GetSelectedItem() { return SelectedItem; } /** Request to reload the text options in the combobox from the OptionsSource attribute */ void RefreshOptions(); /** Clears the selected item in the text combo */ void ClearSelection(); private: TSharedPtr OnGetSelection() const { return SelectedItem; } /** Called when selection changes in the combo pop-up */ void OnSelectionChanged(TSharedPtr Selection, ESelectInfo::Type SelectInfo); /** Helper method to get the text for a given item in the combo box */ FText GetSelectedTextLabel() const; FText GetItemTextLabel(TSharedPtr StringItem) const; private: /** Called to get the text label for an item */ FGetTextComboLabel GetTextLabelForItem; /** The text item selected */ TSharedPtr SelectedItem; /** Array of shared pointers to strings so combo widget can work on them */ TArray& lt; TSharedPtr& gt; Strings; /** The combo box */ TSharedPtr StringCombo; /** Forwarding Delegate */ FOnTextSelectionChanged SelectionChanged; /** Sets the font used to draw the text */ TAttribute& lt; FSlateFontInfo& gt; Font; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
#include "CustomTextComboBox.h" #include "Widgets/Input/SSearchBox.h" void SCustomTextComboBox::Construct(const FArguments& amp; InArgs) { SelectionChanged = InArgs._OnSelectionChanged; GetTextLabelForItem = InArgs._OnGetTextLabelForItem; Font = InArgs._Font; // Then make widget this - > ChildSlot [ SAssignNew(StringCombo, SCustomComboBox) .ComboBoxStyle(InArgs._ComboBoxStyle) .ButtonStyle(InArgs._ButtonStyle) .OptionsSource(InArgs._OptionsSource) .OnGenerateWidget(this, & SCustomTextComboBox::MakeItemWidget) .OnSelectionChanged(this, & SCustomTextComboBox::OnSelectionChanged) .OnComboBoxOpening(InArgs._OnComboBoxOpening) .InitiallySelectedItem(InArgs._InitiallySelectedItem) .ContentPadding(InArgs._ContentPadding) [ SNew(STextBlock) .ColorAndOpacity(InArgs._ColorAndOpacity) .Text(this, & SCustomTextComboBox::GetSelectedTextLabel) .Font(InArgs._Font) ] ]; SelectedItem = StringCombo - > GetSelectedItem(); } FText SCustomTextComboBox::GetItemTextLabel(TSharedPtr StringItem) const { if (!StringItem.IsValid()) { return FText::GetEmpty(); } return FText::FromString( (GetTextLabelForItem.IsBound()) ? GetTextLabelForItem.Execute(StringItem) : *StringItem ); } FText SCustomTextComboBox::GetSelectedTextLabel() const { TSharedPtr StringItem = StringCombo - > GetSelectedItem(); return GetItemTextLabel(StringItem); } TSharedRef SCustomTextComboBox::MakeItemWidget(TSharedPtr StringItem) { check(StringItem.IsValid()); return SNew(STextBlock) .Text(this, & SCustomTextComboBox::GetItemTextLabel, StringItem) .Font(Font); } void SCustomTextComboBox::OnSelectionChanged(TSharedPtr Selection, ESelectInfo::Type SelectInfo) { if (Selection.IsValid()) { SelectedItem = Selection; } SelectionChanged.ExecuteIfBound(Selection, SelectInfo); } void SCustomTextComboBox::SetSelectedItem(TSharedPtr NewSelection) { StringCombo - > SetSelectedItem(NewSelection); } void SCustomTextComboBox::RefreshOptions() { StringCombo - > RefreshOptions(); } void SCustomTextComboBox::ClearSelection() { StringCombo - > ClearSelection(); } |
インクルードするファイルと生成するクラスの型が変わっていますが基本的な機能はそのままです。
前回作ったファイルのSTextComboBoxを指定していた部分をSCustomTextComboBoxにさしかえます。 併せてインクルードするファイルも新規のクラスが記述されているものに差し替えます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "DetailCustomizations.h" #include "IPropertyTypeCustomization.h" #include "CustomDisplayList.h" #include "CustomTextComboBox.h" /** * */ class TESTED_API ICustomDetailBase : public IPropertyTypeCustomization { public: /** IPropertyTypeCustomization interface */ virtual void CustomizeHeader(TSharedRef inStructPropertyHandle, class FDetailWidgetRow& amp; HeaderRow, IPropertyTypeCustomizationUtils& amp; StructCustomizationUtils) override; virtual void CustomizeChildren(TSharedRef inStructPropertyHandle, class IDetailChildrenBuilder& amp; StructBuilder, IPropertyTypeCustomizationUtils& amp; StructCustomizationUtils) override; private: TSharedPtr StructPropertyHandle; TSharedPtr KeyHandle; TSharedPtr KeyComboBox; void OnStateValueChanged(TSharedPtr ItemSelected, ESelectInfo::Type SelectInfo); void OnStateListOpened(); void OnCheckStateChanged(ECheckBoxState CheckState); TSharedPtr PropertyUtilities; protected: TArray& lt; TSharedPtr& gt; DisplayStrings; virtual void SetDisplayStrings() = 0; }; // キャラクターステータス用 class TESTED_API ICharacterStatusDetail : public ICustomDetailBase { public: static TSharedRef MakeInstance() { return MakeShareable(new ICharacterStatusDetail()); } protected: virtual void SetDisplayStrings() override { // ピンと同じ処理を使う CustomDisplayList::GetCharacterStatusDisplayStrings(DisplayStrings); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
// Fill out your copyright notice in the Description page of Project Settings. #include "CustomDetail.h" #include "SCheckBox.h" #include "PropertyHandle.h" #include "DetailWidgetRow.h" #include "IPropertyUtilities.h" void ICustomDetailBase::CustomizeHeader(TSharedRef inStructPropertyHandle, class FDetailWidgetRow& amp; HeaderRow, IPropertyTypeCustomizationUtils& amp; StructCustomizationUtils) { StructPropertyHandle = inStructPropertyHandle; DisplayStrings.Add(MakeShareable(new FString("None"))); // 派生先で文字列の一覧を取得してくる SetDisplayStrings(); uint32 NumChildren; StructPropertyHandle - > GetNumChildren(NumChildren); FName Key; for (uint32 ChildIndex = 0; ChildIndex & lt; NumChildren; ++ChildIndex) { const TSharedPtr& lt; IPropertyHandle& gt; ChildHandle = StructPropertyHandle - > GetChildHandle(ChildIndex); if (ChildHandle - > GetProperty() - > GetName() == TEXT("Key")) { KeyHandle = ChildHandle; ChildHandle - > GetValue(Key); } } check(KeyHandle.IsValid()); // 取得してきたKeyがリストの中にあるかチェック int Index = 0; bool Found = false; for (int32 i = 0; i & lt; DisplayStrings.Num(); ++i) { if (DisplayStrings[i] - > Equals(Key.ToString())) { Index = i; Found = true; break; } } if (!Found) { Key = TEXT("None"); KeyHandle - > SetValue(Key); UE_LOG(LogTemp, Error, TEXT("ICustomDetailBase: %s 設定していた文字列が一覧から見つかりませんでした。再指定して下さい"), *Key.ToString()); } HeaderRow .NameContent() [ StructPropertyHandle - > CreatePropertyNameWidget() ] .ValueContent() .MinDesiredWidth(500) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .HAlign(HAlign_Left) [ SAssignNew(KeyComboBox, SCustomTextComboBox) .OptionsSource(& DisplayStrings) .OnSelectionChanged(this, & ICustomDetailBase::OnStateValueChanged) .InitiallySelectedItem(DisplayStrings[Index]) ] ]; } void ICustomDetailBase::CustomizeChildren(TSharedRef inStructPropertyHandle, class IDetailChildrenBuilder& amp; StructBuilder, IPropertyTypeCustomizationUtils& amp; StructCustomizationUtils) { } void ICustomDetailBase::OnStateValueChanged(TSharedPtr ItemSelected, ESelectInfo::Type SelectInfo) { if (ItemSelected.IsValid()) { if (DisplayStrings.Find(ItemSelected)) { KeyHandle - > SetValue(FName(**ItemSelected)); } } } void ICustomDetailBase::OnStateListOpened() { } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
// Fill out your copyright notice in the Description page of Project Settings. #include "CustomGraphPin.h" #include "KismetEditorUtilities.h" #include "CustomTextComboBox.h" TSharedRef SCustomGraphPinBase::GetDefaultValueWidget() { DisplayStrings.Add(MakeShareable(new FString(TEXT("None")))); // 派生先で文字列の一覧を取得してくる SetDisplayStrings(); int Index = 0; FString CurrentDefault = GraphPinObj - > GetDefaultAsString(); if (CurrentDefault.Len() & gt; 0) { int32 StartIndex = 5; int32 EndIndex; CurrentDefault.FindLastChar(')', EndIndex); FString DefaultValString = CurrentDefault.Mid(StartIndex, EndIndex - StartIndex); // 設定されていた値からインデックスの検索 bool Found = false; for (int32 i = 0; i & lt; DisplayStrings.Num(); ++i) { if (DisplayStrings[i] - > Equals(DefaultValString)) { Index = i; Key = FName(*DefaultValString); Found = true; break; } } if (!Found) { FString TempString = *(DisplayStrings[0]); Key = FName(*TempString); UE_LOG(LogTemp, Error, TEXT("SCustomGraphPinBase: %s 設定していた文字列が一覧から見つかりませんでした。再指定して下さい"), *DefaultValString); } } else { FString TempString = *(DisplayStrings[0]); Key = FName(*TempString); } // リストになるようなウィジェットを生成する return SNew(SVerticalBox) .Visibility(this, & SGraphPin::GetDefaultValueVisibility) + SVerticalBox::Slot() .HAlign(HAlign_Left) [ SNew(SCustomTextComboBox) .OptionsSource(& DisplayStrings) .OnSelectionChanged(this, & SCustomGraphPinBase::OnValueChanged) .InitiallySelectedItem(DisplayStrings[Index]) ]; } void SCustomGraphPinBase::OnValueChanged(TSharedPtr ItemSelected, ESelectInfo::Type SelectInfo) { if (ItemSelected.IsValid()) { if (DisplayStrings.Find(ItemSelected)) { Key = FName(*(*ItemSelected)); SetValue(Key); } else { UE_LOG(LogTemp, Error, TEXT("CustomGraphPinBase:%s 値変更時に選択した名前が一覧から見つかりませんでした"), *(*ItemSelected)); } } } void SCustomGraphPinBase::SetValue(FName InKey) { FString strKey = InKey.ToString(); FString KeyString = TEXT("("); KeyString += TEXT("Key="); KeyString += strKey; KeyString += TEXT(")"); GraphPinObj - > GetSchema() - > TrySetDefaultValue(*GraphPinObj, KeyString); } void SCustomGraphPinBase::CustomGraphPin_OnPluginSearchTextChanged(const FText& amp; NewText) { FilterString = NewText.ToString(); } |
これで完成です。