How to set widget position to cursor position? C++

I’ve been struggling with this for days now.
I need a custom cursor on-screen at all times. I already have the cursor coordinates, but I don’t know how to get the UMG Widget objects and change its properties.

I have a UMG Widget blueprint with an Image object. I want to set the image position and texture within a C++ class.

Also which is the best class to use for main menus and cursors? Should I use a HUD class? I’m currently experimenting inside the PlayerController class.


#pragma once

#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "MyPlayerController.generated.h"

 * Used for HUD controls, Main Menu, Inventory.
class CPP_PROTOTYPE_API AMyPlayerController : public APlayerController

    virtual void Tick(float DeltaTime) override;
		float MouseXPos;
		float MouseYPos;


#include "MyPlayerController.h"
#include "Kismet/GameplayStatics.h" // temp

void AMyPlayerController::Tick(float DeltaTime)
	GetMousePosition(MouseXPos, MouseYPos);
	UE_LOG(LogTemp, Warning, TEXT("Mouse Location: %f, %f"), 
    MouseXPos, MouseYPos);

UCanvasPanelSlot has the function SetDesiredPosition(FVector2D).

The widget that you want to call this function from needs to be a slot (which is like a child but for the UMG layout hierarchy) of UCanvasPanel.

Then you get the slot from that widget, and cast that to UCanvasPanelSlot, from there you can call SetDesiredPosition() and pass in the FVector2D from the PlayerController’s function to get mouse FVector2D.

For example, let’s say you want to adjust the location of a UUniformGridPanel to the mouse position.

UUniformGridPanel has to be a slot of a UCanvasPanel.

UUniformGridPanel* MyGridPanel;
UCanvasPanelSlot* GridAsPanelSlot = Cast<UCanvasPanelSlot>(MyGridPanel->Slot);

Something along those lines.

1 Like