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

如何在Godot中实现全文搜索?已创建LineEdit并绑定TextChanged信号

在Godot里实现LineEdit驱动的全文搜索

基本逻辑

利用LineEdit的text_changed信号,每次输入内容变化时,遍历VBoxContainer里的所有子控件,检查控件文本是否包含搜索关键词,然后控制控件的显示/隐藏。

具体操作步骤

1. 编写信号处理函数

把下面的函数加到你的脚本里(脚本挂在VBoxContainer或者它的父节点都可以):

func _on_search_text_changed(new_text: String) -> void:
    # 处理搜索关键词:去首尾空格+转小写,实现不区分大小写搜索
    var search_key = new_text.strip_edges().to_lower()
    # 遍历VBoxContainer下的所有子节点
    for child in $VBoxContainer.get_children():
        # 只处理带text属性的控件(比如按钮、标签)
        if child.has("text"):
            var child_text = child.text.strip_edges().to_lower()
            # 空关键词时显示所有内容,否则只显示包含关键词的项
            child.visible = search_key == "" || child_text.find(search_key) != -1

2. 确认信号连接

  • 如果你是在编辑器信号面板连的text_changed,确保已经把信号绑定到上面这个函数。
  • 要是用代码连接,就在_ready()里加一行:
func _ready() -> void:
    $LineEdit.connect("text_changed", self, "_on_search_text_changed")

3. 可选优化

  • 模糊搜索:要是想做模糊匹配,把判断里的find换成similarity函数,比如:
    child.visible = search_key == "" || child_text.similarity(search_key) > 0.5
    
    数值0.5可以自己调整,越高匹配度要求越严格。
  • 关键词高亮:如果需要高亮显示匹配的部分,把普通Label换成RichTextLabel,然后修改处理逻辑:
    if child is RichTextLabel:
        var original_text = child.text.strip_edges()
        if search_key != "":
            var lower_text = original_text.to_lower()
            var start_idx = lower_text.find(search_key)
            if start_idx != -1:
                var highlight_part = original_text.substr(start_idx, search_key.length())
                child.bbcode_text = original_text.replace(highlight_part, "[color=#4287f5]" + highlight_part + "[/color]")
            else:
                child.bbcode_text = original_text
        else:
            child.bbcode_text = original_text
    

内容的提问来源于stack exchange,提问作者фор евер

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:12:16