Can a UMG button trigger an event defined by a c++ function?

Hi,there. I’m trying to create a menu with UMG. And it contains a few buttons.

Here is what i want to do with the button:
When I press it, an exe profile excutes. According to what i’ve learned, I could use FMonitoredProcess class to call the windows commander. So i want to write a C++ function to call the exe program.

And here is the problem:
How can i make the C++ function an event which could be used by the button. How to relate the button with the function?

Probably the best approach for utility/stateless functions would be to use a Blueprint Function Library. Essentially you wrap your C++ code into a function with the desired parameters and expose it in the function library and then it will be globally accessible from anywhere (just right click on the event graph).

From the blueprint perspective once you have the function defined, you would have your UMG button just call the function you defined.

More resources: wiki example on how to use a blueprint function library.

Hi, thank you for answering. It’s really helpful. But when I don’t define it as a static function, then I can’t get the function in my event graph. So Why does it have to be static function? Do you have any ideas?

It’s by definition a collection of static methods, which makes it easy to call from anywhere.

Unless you have a compelling reason to have a member then I would recommend sticking with Blueprint Libraries.

If you do need a member function, I generally recommend using an ActorComponent attached to your actor and then getting a reference to the actor,then you could access the component via Actor->ActorComponent. You would put your custom methods on that component. Here’s an example of a C++ actor component:

UCLASS(meta=(BlueprintSpawnableComponent))
class UCustomComponent : public UActorComponent
{
	GENERATED_UCLASS_BODY()
public:
	UFUNCTION(BlueprintCallable)
	void MyFunction();
}

Another option is to define a UObject/AActor C++ class as a BlueprintType e.g.

UCLASS(BlueprintType)
class USubObject : public UObject
{
	GENERATED_UCLASS_BODY()
public:
	UFUNCTION(BlueprintCallable)
	void MyFunction();
}

That would make it accessible from blueprint, but you would need to create the object or spawn the actor to use it. One way would be by adding a static create method which you could then call in Blueprint e.g.

 //.h
 UFUNCTION(BlueprintCallable)
 static USubObject* CreateSubObject(UObject* owner);
 
//.cpp
 USubObject* USubObject::CreateSubObject(UObject* owner)
 {
     return NewObject<USubObject>(owner);
 }

Thanks a lot. I will try these methods later. :slight_smile: