I have a panel with a StyleBox applied in "theme overrides". How do I programmatically change its background color?
I'm answering my own question because I hope that this can be helpful to other users. I've searched across many internet pages, and it seems the way to achieve this is not so clear. It took me a while to understand how to properly do what seems to be a basic thing, so I'm leaving this answer here hoping it can be found by who searches for it.
I have this panel that I use as a "prefab", meaning that I instantiate multiple instances of it via code, and I wanted to change each instance's background separately.
In order to achieve this, you have to get the current styleBox you're using to override the theme of your panel first (you can even create a new one if that's useful to you, but in my case I just wanted to change BG Color and keep everything else as it was).
var styleBox: StyleBoxFlat = get_theme_stylebox("panel")
Note that this script is directly attached to my panel, that's why I'm calling directly "get_theme_stylebox" without referencing any panel.
Also, since that is the same styleBox being used on ALL of the instances of this panel that I create, I added ".duplicate()" to get a duplicate of this styleBox.
var styleBox: StyleBoxFlat = get_theme_stylebox("panel").duplicate()
Do this too if you don't want all of the panel instances to get the changes you're making.
Note that
"panel"
in the line of code above. That is the name of the StyleBox you create via inspector, and you can find it by hovering your mouse above the "Panel" under Theme Overrides in the inspector:
After that, you can change your styleBox as you want. In my case I just wanted to change its color, so I used this:
styleBox.set("bg_color", Color(1.0, 0.0, 0.0))
Also here, note that "bg_color". That is the name of the property I want to change. You can get it the same way you get the panel's name: by hovering your mouse on it, in the inspector.
Finally, you just attach the edited StyleBox to the panel by writing:
add_theme_stylebox_override("panel", styleBox)
© 2022 - 2024 — McMap. All rights reserved.