Please nominate your Qt Champions for 2021!

how to highlight selected text in QTextEdit?

  • I has realised a small app like NoteBook.Now,I want to hight selected text,but I have no idea about this. I create a class that inheit QSyntaxHighlighter.

    //your code here
    class Myhighlitghter : public QSyntaxHighlighter
        explicit Myhighlitghter(QTextDocument *parent=0);
         virtual void highlightBlock(const QString &text);
    Myhighlitghter::Myhighlitghter(QTextDocument *parent)
    void Myhighlitghter::highlightBlock(const QString &text)
        QTextCharFormat charformat;
        QString pattern="\\bchar\\b";
        QRegExp exp(pattern);
        int index = text.indexOf(exp);
            int len=exp.matchedLength();
            index = text.indexOf(exp,index+len);

    then I create a mainwindow that has Qtextedit and Myhighlitghter object.Now , I want to select text in textedit and hightlight them.

    thank for your help

  • @chaochao

    QTextCursor will help you to select the text, delete , replace, background color of the selected text.

  • @Ni.Sumi very thanks, I will have a try

Log in to reply