Search code examples
c++user-interfacewidgetunreal-engine5

UE5/C++ Progress Bar: Change a background image during runtime


I'm quite new to UE, so I'm seeking for some help! Currently I'm working on HUD and faced some issues with Progress Bars. The goal is pretty simple, I need to change a background image of Progress Bar during runtime. According to my logging everything is working but it doesn't show any changes on Screen. I appreciate any help!

My code:

.h

    UPROPERTY(EditAnywhere, meta=(BindWidget))
    class UProgressBar* IconSlot1;
    UPROPERTY(EditAnywhere, meta=(BindWidget))
    class UProgressBar* IconSlot2;
    UPROPERTY(EditAnywhere, meta=(BindWidget))
    class UProgressBar* IconSlot3;
    UPROPERTY(EditAnywhere)
    TArray<class UIconSlot*> IconArr;
    UPROPERTY(VisibleAnywhere)
    TArray<class UProgressBar*> SlotArr;

.cpp

void UPlayerUI::SetSlotIcon(const TEnumAsByte<EDamageClass>& DamageClass)
{
    const auto EmptySlot = GetFreeSlot();
    const auto Icon = GetImage(DamageClass);

    if (IsValid(EmptySlot) && IsValid(Icon))
    {
        FProgressBarStyle Style = EmptySlot -> GetWidgetStyle();
        
            if (Style.BackgroundImage.GetResourceObject() == nullptr)
            {
                FSlateImageBrush Brush = FSlateImageBrush(Icon, FVector2d(100, 100));
                Style.SetBackgroundImage(Brush);
                UE_LOG(LogTemp, Warning, TEXT("Image slot is set"));
            }
            else
            {
                UE_LOG(LogTemp, Warning, TEXT("Image slot isn't empty"));
                return;
            }

            Slots.Add(EmptySlot, DamageClass);
    }
}
UProgressBar* UPlayerUI::GetFreeSlot()
{
    for (const auto IconSlot : SlotArr)
    {
        if (!Slots.Contains(IconSlot))
        {
            UE_LOG(LogTemp, Warning, TEXT("Slot found"));
            return IconSlot;
        }
    }
    
    return nullptr;
}
UTexture2D* UPlayerUI::GetImage(const TEnumAsByte<EDamageClass>& DamageClass)
{
    for (const auto IconImage : IconArr)
    {
        if (IconImage -> DamageClass == DamageClass && !Icons.Contains(IconImage))
        {
            UE_LOG(LogTemp, Warning, TEXT("Image found"));
            Icons.Add(IconImage, DamageClass);
            return IconImage -> Image;
        }
    }
    
    return nullptr;
}

Solution

  • Resolved it by adding these lines:

    Style = Style.SetBackgroundImage(Brush);
    EmptySlot -> SetWidgetStyle(Style);