Change the stylebox of a node via code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By psear

I have a grid of various UI items, and depending on some variable in the backend, some of them will or won’t have a shaded cell behind them. I’m trying to do something like this, like if I am changing the normal style of a button:

var some_stylebox = preload("pathtostylebox")
$example_button.normal = some_stylebox

But I just get an error saying I can’t set “normal” to type “stylebox”. I get that the normal stylebox is a property of the theme and not the button, but if I change the whole theme that will affect all buttons with that theme.

TLDR: I want to set the stylebox for a button without affecting all the other buttons with that theme, how do I do that?

:bust_in_silhouette: Reply From: estebanmolca

Check the methods of the Control class in the manual. I think this is what you are looking for:
void add_stylebox_override ( StringName name, StyleBox stylebox )
Overrides the StyleBox with given name in the theme resource the control uses. If stylebox is empty or invalid, the override is cleared and the StyleBox from assigned Theme is used.


…Just out of curiosity, what would be the translation of TLDR?

estebanmolca | 2020-06-14 14:15

Thanks, this is exactly what I was looking for.
TLDR means “Too long, didn’t read”, and is a short summary for people who don’t want to read the full post.

psear | 2020-06-14 17:35

:bust_in_silhouette: Reply From: Nothing:D

So the previous answer of using add_stylebox_override works, but if the stylebox already has an override, you can also use Stylebox get_stylebox( name: String, theme_type: String = "" ) to get the stylebox then modify the returned stylebox directly.
For example:
get_stylebox("normal").bg_color = will change the background color of the normal styled button to red (note: only StyleBoxFlat has bg_color property).

This was useful to me because then I could easily use Tweens to transition between colors:

$Tween.interpolate_property(get_stylebox("normal"), "bg_color",,
1 Like