When working with Slate in Unreal Engine it’s often needed to share styles between multiple widgets or easily reference content (such as images). A quick way to do this is to store styles in a FSlateStyleSet object.
Creating a Style Set
Style sets can be defined virtually anywhere, but the pattern I like to use is to wrap the style set into a class that provides access to it in a singleton-like way.
The Initialize and Shutdown methods should be called when the module that contains the style set is loaded and unloaded. This ensures that our style set exists and can be accessed safely as long as its module is loaded.
Style sets can contain virtually any type of styling information including brushes, margins and widget styles such as FTextBlockStyle for STextBlock, FButtonStyle for SButton, etc. Let’s look at a few examples:
Since defining brushes can become fairly verbose, most stylesheets in the engine use macros to cut down on the boilerplate:
Whether to use this approach really boils down to personal preference. Regardless of that, let’s take a moment to appreciate the fact that Unreal Engine 5 finally supports loading SVG files. Very nice!
Using images from a plugin or the project
So far we’ve only used assets that come with the engine, but what if we wanted to use custom assets? The first step is to put them in the plugin’s (or project’s) Content folder — or Content/Slate in case we want to make the content available in cooked builds.
After that, it’s simply a matter of referencing our content. To do this, let’s define two additional helpers on our style set:
These functions can be used directly or wrapped in macros similar to the ones above:
Styles defined via style sets can be accessed directly using one of the corresponding getters, such as GetBrush, GetMargin, etc. Some widgets also support specifying the styleset and the style name directly, without having to call one of the getter functions.
Bonus: using Unreal Editor styles
It’s interesting to note that the whole editor is styled via style sets. You can find the most recent styles (added in UE5) in FStarshipEditorStyle, but some styles can still be found in legacy style sets from the UE4 era, such as FSlateEditorStyle.
Regardless of where they’re defined, built-in styles can be accessed via FAppStyle, for example: