OptionButton
2026/4/14大约 2 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — OptionButton
OptionButton
节点继承关系
继承链:Node → CanvasItem → Control → BaseButton → OptionButton
定义
一个下拉选择框——就像网页里的 <select>,点击后展开一个列表让你选一项。选完后按钮上显示你选的内容。
使用频率:★★★ 一般常用(需要从多个选项中选一个时使用)
节点用途
- 让用户从预设列表中选择一个选项
- 难度选择、语言选择、分辨率选择等
使用场景
- 设置菜单中的难度选择(简单/普通/困难)
- 游戏开始前的角色选择
- 图形设置中的分辨率选择
常用节点搭配
- 搭配
Label显示选项标题 - 搭配
HBoxContainer排列选项
生效必备素材/资源
无需特殊资源。选项在代码或编辑器中添加。
节点属性与信号
自有属性
| 属性 | 类型 | 默认值 | 继承自 | 说明 |
|---|---|---|---|---|
selected | int | -1 | — | 当前选中的选项索引 |
item_count | int | 0 | — | 选项总数(只读) |
fit_to_longest_item | bool | false | — | 按钮宽度是否适配最长的选项文字 |
继承自 BaseButton
| 属性 | 类型 | 默认值 | 继承自 | 说明 |
|---|---|---|---|---|
disabled | bool | false | BaseButton | 是否禁用 |
信号
| 信号 | 触发时机 | 参数 |
|---|---|---|
item_selected | 用户选择了一个选项时 | int 选中项的索引 |
pressed | 按钮被点击时 | 无 |
常用方法
| 方法 | 说明 |
|---|---|
AddItem("文字", id) | 添加一个选项 |
GetSelected() | 获取当前选中的选项 ID |
Select(id) | 设置选中项 |
GetItemCount() | 获取选项总数 |
GetItemText(index) | 获取指定索引的选项文字 |
Clear() | 清空所有选项 |
RemoveItem(index) | 移除指定选项 |
代码示例
C
using Godot;
public partial class OptionButtonDemo : Control
{
public override void _Ready()
{
var optionBtn = new OptionButton();
optionBtn.Position = new Vector2(100, 100);
// 添加选项
optionBtn.AddItem("简单", 0);
optionBtn.AddItem("普通", 1);
optionBtn.AddItem("困难", 2);
// 默认选中"普通"
optionBtn.Select(1);
// 监听选择变化
optionBtn.ItemSelected += (index) =>
{
GD.Print($"选择了难度索引: {index}");
};
AddChild(optionBtn);
}
}GDScript
extends Control
func _ready():
var option_btn = OptionButton.new()
option_btn.position = Vector2(100, 100)
# 添加选项
option_btn.add_item("简单", 0)
option_btn.add_item("普通", 1)
option_btn.add_item("困难", 2)
# 默认选中"普通"
option_btn.select(1)
# 监听选择变化
option_btn.item_selected.connect(func(index: int):
print("选择了难度索引: " + str(index))
)
add_child(option_btn)