how to override button style in code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Qws
var redbtnstyle = load("res://Themes/Button/RedButton.tres")
get_node("./Button").add_style_override("RedButton", redbtnstyle)

“RedButton.tres” is a theme file I created by saving my custom theme in the editor. I’m loading it into a variable and that variable should be used to override my button style.

But I can’t load the theme file in through code, it says that the style is empty, but it does work when I do it with the editor/inspector…

Example project (godot 2)

:bust_in_silhouette: Reply From: Aimarekin

This question was done for Godot 2, so I don’t know how it worked back then, but if anyone using Godot 3 stumbles upon this question, take a look at the docs for Control, particularly the functions containing override.

To add an override, use one of the functions called add_*_override, replacing * with the item you want replaced. As arguments, you’ll have to provide the name of the custom style property you want replaced. So for example, a Label has one style override, which is called custom_styles/normal and contains a StyleBox. We’d use:

Label.add_stylebox_override("normal", my_style_box) # Overrides the normal style with my_style_box

This will replace the previous override as well. There’s other similar functions like get_*. Use this in conjunction with .duplicate() to make unique overrides for all your instances, like so:

var new_style_box:StyleBoxFlat = Label.get_stylebox("normal").duplicate() # Gets the current stylebox, overriden or not for normal and duplicates it (This will only work if one is already set!)
new_style_box.bg_color = Color(1,0,0,1) # Changes the duplicate's color to red
Label.add_stylebox_override("normal", new_style_box) # Now we have replaced the override with our new, red one