虚幻4中用C++代码创建UI控件

1.加载UserWidget

void AUserWidgetContainer::CreateUserWidgetInstance(EUserWidget name, const FString path)
{
	UClass* widgetClass = LoadClass(nullptr, path.GetCharArray().GetData());
	UUserWidget* userWidget = CreateWidget(GetWorld(), widgetClass);
	userWidgetMap.Emplace(name, userWidget);
}

2.创建Button

void AUserWidgetContainer::ConstructButtonWidget(EUserWidget userWidget, FString widgetName, FVector2D location, FVector2D size, float angle)
{
	UCanvasPanel* canvasPanel = (UCanvasPanel*)userWidgetMap[userWidget]->GetWidgetFromName(TEXT("WidgetName"));
	UButton* widget = userWidgetMap[userWidget]->WidgetTree->ConstructWidget(UButton::StaticClass(), FName(*widgetName));
	canvasPanel->AddChild(widget);

	UStructWidget* tempStructure = NewObject(GetTransientPackage(), UStructWidget::StaticClass());
	tempStructure->widgetName = widgetName;
	tempStructure->belong = userWidget;

	Cast(widget->Slot)->SetAlignment(FVector2D(0.5, 0.5));
	Cast(widget->Slot)->SetPosition(location);
	Cast(widget->Slot)->SetSize(size);
	widget->SetRenderAngle(angle);
        //设置button样式
	FButtonStyle style;
	FSlateBrush brush;
	brush.SetResourceObject(StaticLoadObject(UTexture2D::StaticClass(), NULL, TEXT("Texture2D'/Game/Textures/texturename'")));
	style.SetNormal(brush);
	style.SetHovered(brush);
	style.SetDisabled(brush);
	style.SetPressed(brush);
	widget->SetStyle(style);
}

3.创建数据结构




你可能感兴趣的:(虚幻引擎)