Adding panel via script, no background

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

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.

:bust_in_silhouette: Reply From: jgodfrey

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)

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.

dhuzud | 2020-02-22 08:52