How to change panel's background color?
Asked Answered
E

1

5

I have a panel with a StyleBox applied in "theme overrides". How do I programmatically change its background color?

Exude answered 26/1 at 13:34 Comment(0)
E
10

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)
Exude answered 26/1 at 13:34 Comment(2)
Wow, a timely answer. Thanks for the update and useful answer. I'm learning most of the customization of the UI is just in the theme.Adeno
Yes, it's pretty simple actually, but if you come from other engines as Unity it can be confusing at first. More than that, the official Godot documentation isn't much clear on this part, there is no example on how to achieve this via code, since it's a method of the parent class Control and they just put a generic example on how to change font color in case of a simple Label.Exude

© 2022 - 2024 — McMap. All rights reserved.