UE – Slate 注册选项菜单

内容纲要

注册 Slate 右键菜单

file

按下右键后打开菜单(Runtime 或 Editor)


1. 新建Commands指令

一般 UI 操作都需要注册一个 Commands 用于存放所有的指令。

例如图示中的 Remove Clip 就是一条指令。

// TimelineClipCommands.h
class FTimelineClipCommands : public TCommands<FTimelineClipCommands>
{
public:
    FTimelineClipCommands()
        : TCommands<FTimelineClipCommands>(TEXT("FTimelineClipCommands"), NSLOCTEXT("Contexts", "FTimelineClipCommands", "FTimelineClipCommands"), NAME_None, FAppStyle::GetAppStyleSetName())

    // TCommands<> 接口
    virtual void RegisterCommands() override;

    // 这个 Remove 变量是其中的一条指令,也就是Remove Clip
    TSharedPtr<FUICommandInfo> Remove;
};
// TimelineClipCommands.cpp
#include "TimelineClipCommands.h"
#define LOCTEXT_NAMESPACE "FTimelineClipCommands"
void FTimelineClipCommands::RegisterCommands()
{
// 这里的 "Remove Clip" 是菜单显示名字
    UI_COMMAND(Remove, "Remove Clip", "Executes My TimelineClipCommands", EUserInterfaceActionType::Button, FInputChord());
}
#undef LOCTEXT_NAMESPACE

2. 到对应 Slate 中注册菜单

在 Construct 函数中做一些操作。

// 初始化命令,很重要否则 Get 会导致崩溃。
FTimelineClipCommands::Register();
// 初始化指令列表(记得去h文件里定义这个)
CommandList = MakeShareable(new FUICommandList);
// 直接将 Action Map 到这个 Lambda 上,执行时便会调用Lambda的内容
CommandList->MapAction(FTimelineClipCommands::Get().Remove, FExecuteAction::CreateLambda([]()
{

}), FCanExecuteAction());

3. 打开菜单

打开菜单操作需要有事件触发,例如我们绑定右键打开菜单

TSharedPtr<SWidget> MenuContent;
if (PointerEvent.IsMouseButtonDown(EKeys::RightMouseButton))
{
    // 先构建一个 MenuBuilder 用于添加指令到上面。
    FMenuBuilder MenuBuilder(true, CommandList);
    MenuBuilder.AddMenuEntry(FTimelineClipCommands::Get().Remove);
    MenuContent = MenuBuilder.MakeWidget();

    // 将菜单通过 UE 的接口添加上去,至此你已经创建成功了
    FSlateApplication::Get().PushMenu(AsShared(), FWidgetPath(), MenuContent.ToSharedRef(), FSlateApplication::Get().GetCursorPos(),    FPopupTransitionEffect::ContextMenu);
}

Related Posts

发表回复

同步Schの秘密防空洞