Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Slate UI Widget implementation
#include "SGreetings.h"
#include "SlateOptMacros.h"
#include "Widgets/Input/SEditableTextBox.h"
#define LOCTEXT_NAMESPACE "SGreetings"
const TArray<FText> SGreetings::Titles =
{
LOCTEXT("Mr", "Mr."),
LOCTEXT("Mrs", "Mrs."),
LOCTEXT("Ms", "Ms."),
};
BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION
void SGreetings::Construct(const FArguments& InArgs)
{
SelectedTitle = MakeShareable(new FText(Titles[0]));
for (const auto& Title : Titles)
{
TitleOptions.Add(MakeShareable(new FText(Title)));
}
TSharedPtr<SComboBox<TSharedPtr<FText>>> TitleComboBox;
ChildSlot
[
SNew(SBorder)
.BorderImage(InArgs._Background)
.Padding(FMargin(20))
[
SNew(SVerticalBox)
+SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+SHorizontalBox::Slot()
[
SAssignNew(TitleComboBox, SComboBox<TSharedPtr<FText>>)
.InitiallySelectedItem(SelectedTitle)
.OptionsSource(&TitleOptions)
.OnSelectionChanged_Lambda([this](TSharedPtr<FText> NewSelection, ESelectInfo::Type SelectInfo)
{
SelectedTitle = NewSelection;
})
.OnGenerateWidget_Lambda([](TSharedPtr<FText> Option)
{
return SNew(STextBlock)
.Font(FCoreStyle::GetDefaultFontStyle("Regular", 18))
.Text(*Option);
})
[
SNew(STextBlock)
.Font(FCoreStyle::GetDefaultFontStyle("Regular", 18))
.Text_Lambda([this]()
{
return SelectedTitle.IsValid() ? *SelectedTitle: FText::GetEmpty();
})
]
]
+SHorizontalBox::Slot()
.Padding(5, 0)
[
SAssignNew(NameBox, SEditableTextBox)
.Font(FCoreStyle::GetDefaultFontStyle("Regular", 18))
.HintText(LOCTEXT("YourName", "Fill your name"))
]
+SHorizontalBox::Slot()
.Padding(5, 0)
[
SNew(SButton)
.OnClicked(this, &SGreetings::Greet)
[
SNew(STextBlock)
.Font(FCoreStyle::GetDefaultFontStyle("Regular", 18))
.Text(LOCTEXT("Hello", "Hello!"))
]
]
]
+SVerticalBox::Slot()
.Padding(0, 10)
[
SAssignNew(GreetBox, STextBlock)
.Font(FCoreStyle::GetDefaultFontStyle("Regular", 18))
]
]
];
}
FReply SGreetings::Greet()
{
GreetBox->SetText(FText::Format(LOCTEXT("GreetingsText", "Hello, {0} {1}!"), *SelectedTitle, NameBox->GetText()));
return FReply::Handled();
}
END_SLATE_FUNCTION_BUILD_OPTIMIZATION
#undef LOCTEXT_NAMESPACE
@unsanedingding
Copy link

unsanedingding commented Apr 29, 2022

Good job! But if i have a layout config of buttons in json file, how to call SNew at runtime by C++ , because SCompoundWidget::Construct function can not run at after read json file.
Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment