Important: Please read the Qt Code of Conduct -

How QTextBrowser highlight line?

  • How to create a function to highlight line from the given line number?


  • You can try something like

    QTextCursor coursor(textBrowser->document()->findBlockByLineNumber(i));
    QTextBlockFormat frmt = coursor.blockFormat();

  • Moderators

  • @VRonin
    Your method can work, but highlight lines one by one, I need only highlight current line i, I use it to highlight song lyrics.
    And can you change the font color but not background color?

  • Me and @raven-worx gave you the two solution based on usage. if you want the highlight to change based on user clicking on the line use @raven-worx solution. if you want the highlight as permanent or changing based on a state (a timer, an event, a button click) then you can use my solution

  • @VRonin
    Clear highlight has been solved.
    But how to change to highlight font color not background?
    QTextBlockFormat.setForeground(QBrush(Qt::yellow)) has no effort.

    // clear
    for(int a=0;a<lyrics.size();a++){
        QTextCursor cursor(ui->textBrowser->document()->findBlockByLineNumber(a));
        QTextBlockFormat TBF = cursor.blockFormat();
    // color it
    QTextCursor cursor1(ui->textBrowser->document()->findBlockByLineNumber(i));
    QTextBlockFormat TBF1 = cursor1.blockFormat();

Log in to reply