Home > Enterprise >  Search String Highlight in qt or qml
Search String Highlight in qt or qml

Time:06-29

I have use case where in text entered in TextField (Qml Component) should highlight all the texts which matches in the list view content.

I have explored many blogs, in every blog I can just see the snippet code. But not the complete usage, so I couldn't find any proper solution. Can anyone help me out with sample working example.

I have attached sample output how I am expecting ExpectedOutput

CodePudding user response:

The simple example using Text as a delegate:

ColumnLayout
{
    anchors.fill: parent
    spacing: 5
    TextField {
        id: input
        Layout.preferredHeight: 30
        Layout.fillWidth: true
    }

    ListView {
        id: list
        Layout.fillHeight: true
        Layout.fillWidth: true
        model: ["aaaa bbbb cccc","dddd aaaa bbbb","cccc bbbb eeee"]
        delegate: Text {
            property string origText: modelData
            text: list.hightlightText(origText)
        }

        function hightlightText(txt)
        {
            var str = input.text;
            var pos = txt.indexOf(str);
            if(pos !== (-1))
            {
                return txt.replace(str,"<font color='#FF0000'>"   str   "</font>")
            }

            return txt;
        }
    }
}

You can style the selection using supported subset of HTML tags.

  • Related