You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot中OptionButton随最长条目自动缩放,如何固定其尺寸?

强制固定Godot OptionButton控件尺寸的方法

OptionButton默认会根据最长选项自动拉伸宽度,以下是几种可靠的解决方式:

1. 属性面板直接配置(基础方案)

  • 打开控件的Rect属性面板:
    • 设置Custom Minimum Size为目标固定尺寸(如(160, 22))
    • 将Size Flags的Horizontal选项改为Fixed(取消Fill/Expand)
    • 开启Clip Content,超出按钮的文字会被截断(下拉菜单仍会正常显示完整选项内容)

2. 代码强制锁定(添加选项后生效)

如果添加选项后属性设置被覆盖,在所有选项加载完成后执行以下代码:

Godot 3.x

# 锁定水平尺寸为固定模式
shell_selection_option_button.size_flags_horizontal = SIZE_FIXED
# 设置固定尺寸
shell_selection_option_button.rect_size = Vector2(160, 22)
# 可选:让下拉菜单自适应选项长度(不影响主按钮)
shell_selection_option_button.get_popup().fit_content()

Godot 4.x

# 锁定水平尺寸为固定模式
shell_selection_option_button.size_flags_horizontal = SizeFlags.FIXED
# 设置固定尺寸
shell_selection_option_button.size = Vector2(160, 22)
# 可选:让下拉菜单自适应选项长度(不影响主按钮)
shell_selection_option_button.get_popup().fit_content()

3. 重写方法彻底禁用自动调整(进阶方案)

如果以上方法仍失效,可以继承OptionButton并重写自动调整宽度的方法,从根源阻止控件拉伸:

Godot 3.x

extends OptionButton

# 重写fit_width方法,空实现阻止自动调整
func fit_width():
    pass

Godot 4.x

extends OptionButton

# 重写fit_width方法,空实现阻止自动调整
override func fit_width():
    pass

使用这个自定义控件替代原生OptionButton后,无论添加多少长选项,都不会自动修改主按钮尺寸,你可以自由设置固定大小。

内容的提问来源于stack exchange,提问作者Grymjack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:10:33