+3 votes

I want to have a simple Panel with buttons on it.

So I made new Panel node, gave it HBoxContainer and put some Buttons inside HBoxContainer.

Problem is – height of my Panel is 0. Buttons are visible, but Panel is not. I can change it manually, but after I tinker with my layout a bit it goes back to 0.

Can I have a Panel that adjusts itself to it's content?

in Engine by (112 points)

I think that's definitely possible, but I don't know how off the top of my head.I will try to fiddle with it in a few hours if you don't get an answer by them.

1 Answer

+11 votes

Try to use PanelContainer, as what a container does is organizing its children automatically. If you use Panel, it won't take care of them.

Here's a sample code for my simple hiearchy:

For testing, simply add / remove a button by pressing action('add') / action('subtract')

extends PanelContainer

# Reference
onready var hbox_container = $HBoxContainer 

# Helper variable
onready var mim_size = rect_size  # get initial size when ready

func _ready():

func _input(event):
    if event.is_action_pressed("add"):

    elif event.is_action_pressed("subtract"):

func add_button():
    var btn = Button.new()
    btn.text = "Button"

func remove_button():
    var ch = hbox_container.get_child(0)
    if ch != null:

func shrink_size():
    rect_size = mim_size

Note that PanelContainer only resizes its rect when it needs to expand, but not when it can shrink. (I guess the dev should add this feature, if I'm not wrong)
So I manually set it to min_size after the button has been hidden.

And you don't necessarily need to do this when handling resize:


you can do:


(the first approach is safer though)


by (44 points)
edited by

And for more gerneral purpose, you can call shrink function when your box container emit sort_children signal, instead of calling shrink when you do an operation everytime.

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 Frequently asked questions and 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.