Qt/QML实现TextField输入匹配ListView内容的搜索高亮
QML实现TextField搜索匹配ListView文本高亮完整方案
核心原理:借助QML Text 组件的富文本渲染能力,对列表项原始文本做全局正则匹配,将命中搜索关键词的文本片段包裹自定义样式的HTML标签,输入框内容变化时实时刷新列表渲染结果,即可实现匹配片段高亮效果。
以下是可直接复制运行的完整代码:
import QtQuick 2.15 import QtQuick.Controls 2.15 import QtQuick.Layouts 1.15 ApplicationWindow { width: 640 height: 480 visible: true title: qsTr("列表搜索高亮演示") // 模拟列表测试数据源 property list<string> demoListData: [ "QML is a declarative user interface markup language", "Qt Quick provides rich visual components for cross-platform application development", "TextField is a commonly used single-line text input control in Qt Quick", "ListView can efficiently display large-scale scrollable data lists", "Highlighting matching text snippets can significantly improve user search experience", "Regular expressions can be used to implement flexible and accurate text matching logic", "Rich text tags support modifying the display style of local text fragments easily" ] ColumnLayout { anchors.fill: parent anchors.margins: 12 spacing: 12 // 搜索输入框 TextField { id: searchInput Layout.fillWidth: true placeholderText: "请输入搜索关键词" selectByMouse: true } // 搜索结果列表 ListView { id: resultListView Layout.fillWidth: true Layout.fillHeight: true spacing: 8 clip: true model: demoListData delegate: Item { width: ListView.view.width height: showText.height + 10 // 列表项背景 Rectangle { anchors.fill: parent color: "#f5f7fa" radius: 4 } // 带高亮效果的文本展示 Text { id: showText anchors { fill: parent margins: 8 } text: { const keyword = searchInput.text.trim() // 关键词为空时直接返回原始文本 if (!keyword) return modelData // 转义正则特殊字符,避免输入特殊符号时匹配异常 const escapeRegExp = /[.*+?^${}()|[\]\\]/g const safeKeyword = keyword.replace(escapeRegExp, '\\$&') // 构造全局不区分大小写的匹配正则 const matchRegExp = new RegExp(`(${safeKeyword})`, 'gi') // 将匹配到的片段替换为带高亮样式的富文本 return modelData.replace(matchRegExp, '<span style="color:#f5222d;background:#fff1f0;border-radius:2px;padding:0 3px;">$1</span>') } textFormat: Text.RichText wrapMode: Text.WrapAtWordBoundaryOrAnywhere } } } } }
自定义调整说明
- 匹配规则:默认是不区分大小写的全局匹配,如果需要严格区分大小写,把构造正则时的参数
'gi'改成'g'即可 - 高亮样式:直接修改
span标签内的CSS属性即可自定义高亮效果,支持调整文字颜色、背景色、圆角、内边距等样式 - 数据源适配:如果你的列表使用自定义数据模型,只需要把代码中取原始文本的
modelData替换为模型中对应的文本字段即可,比如模型存文本的字段为title就替换为model.title - 边界兼容:代码已经做了正则特殊字符转义,输入
*、?、(这类正则保留字符时不会出现匹配报错
内容的提问来源于stack exchange,提问作者Mohammed Sadiq Afreed Meeran
相关产品推荐
相关产品推荐

