0 votes

Godot Engine v3.2.stable.official
Adding a panel via inspector and changing it's color to red works fine through:

var new_style = StyleBoxFlat.new()
new_style.set_bg_color(Color(1, 0, 0, 1))
$Panel.set("custom_styles/panel", new_style)

Using exactly the same approach, but creating the panel through code doesn't seem to work. In fact there is even no default background visible:

var panel = Panel.new()
self.add_child(panel)

var new_style = StyleBoxFlat.new()
new_style.set_bg_color(Color(1, 0, 0, 1))
panel.set("custom_styles/panel", new_style)

What gives? Tried:
- Adjusting the size of this latter panel (default was (0, 0))
- Toggling visibility off/on
- Calling panel.get_stylebox('panel') before and after setting the
stylebox to verify the stylebox has been changed
- Calling panel.update() also doesn't seem to fix it

Missing something obvious? Looks like the panel is there, it's just invisible.

in Engine by (15 points)

1 Answer

+3 votes
Best answer

If I add your code to _ready, I don't see a panel, as you said. But, looking at the instantiated panel in the Remote scene tree, I found all I had to do was set its size in the inspector to see it.

Armed with that info, I added one line to your code, which renders the panel correctly. Here's my working test code:

func _ready():
    var panel = Panel.new()
    panel.rect_size = Vector2(200, 200)  # <-- added this
    self.add_child(panel)

    var new_style = StyleBoxFlat.new()
    new_style.set_bg_color(Color(1, 0, 0, 1))
    panel.set("custom_styles/panel", new_style)
by (12,282 points)
edited by

Thanks, it seems specifying the sizes is the key!

I was initially creating the panel under a MarginContainer, also created through code.
It turns out this MarginContainer also had a size of Vector2(0, 0) as default.
Therefore no matter what I set as the size of the panel, it would not be rendered.
Specifying the size of the MarginContainer first results in the panel being scaled to be the size of the MarginContainer.

What confused me was that I assumed the default sizes for these nodes would be the same created through inspector or code.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.