Highlighting search



  • Hi all,

    I want to know how can I highlight a text like Qt Creator does when is searching text.

    Best regards.
    David



  • Take a look at [[Doc:QSyntaxHighlighter]]. If you display text using a [[Doc:QTextDocument]] or [[Doc:QTextEdit]] this might just be what you need.



  • Hi Arnold,

    Thanks for the reply, I use QTextDocument, what I do not know how to is show the yellow box when text is found. Qt Creator uses QSyntaxHighlighter?



  • I cannot say what QtCreator actually uses, but if you display your text using a [[Doc:QTextEdit]] then my suggestion would be that you subclass [[Doc:QSyntaxHighlighter]] and reimplement the highLightBlock method. This method will be called automatically once it is attached to a [[Doc:QTextDocument]]. The idea is that the syntax highlighter knows your search term and can apply a [[Doc:QTextCharFormat]] to the appropriate substring:

    @
    void MySyntaxHighlighter::highLightBlock(const QString& text)
    {
    int index = text.indexOf(searchTerm);
    if (index != -1) {
    QTextCharFormat currentFormat = format(0);
    currentFormat.setBackground(Qt::yellow);
    setFormat(index, searchTerm.length(), currentFormat);
    }
    }
    @

    The code above is untested and shall only give you a basic idea. It is of course a bit oversimplified - it for example does not take into account that there might be more than one occurrence of the search term in a block of text.

    Hope this helps.



  • Yes, it helps.

    Thanks.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.