How QTextBrowser highlight line?



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

    QTextBrowser.highlightLine(i);


  • You can try something like

    QTextCursor coursor(textBrowser->document()->findBlockByLineNumber(i));
    QTextBlockFormat frmt = coursor.blockFormat();
    frmt.setBackground(QBrush(Qt::yellow));
    coursor.setBlockFormat(frmt);
    

  • 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();
        TBF.setBackground(QBrush(Qt::transparent));
        cursor.setBlockFormat(TBF);
    }
    // color it
    QTextCursor cursor1(ui->textBrowser->document()->findBlockByLineNumber(i));
    QTextBlockFormat TBF1 = cursor1.blockFormat();
    TBF1.setBackground(QBrush(Qt::yellow));
    cursor.setBlockFormat(TBF1);
    ui->textBrowser->setTextCursor(cursor1);

Log in to reply
 

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