I have change the color of each line text in QTextWidget one by one



  • I have change the color of each line text in QTextWidget one by one. I have multiple lines QtextEdit .

    Could you please some one suggest how to do that


  • Qt Champions 2017



  • I have lines

    line1
    line2
    line3
    intially lines are not edited

    now I have C++ function

    colorEach:Line() {
    getEachline from QtexLine and
    change the color of ltext in QtextEdit

    }



  • QTextCursor cursor(textEdit->document());
    cursor.movePosition(QTextCursor::Start);
    while(cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::MoveAnchor)){
    QTextCharFormat tempFormat = cursor.charFormat();
    tempFormat.setBackground(Qt::yellow);
    cursor.setCharFormat(tempFormat);
    cursor.movePosition(QTextCursor::NoMove); //this might need to be cursor.movePosition(QTextCursor::NextCharacter) unsure
    }
    


  • @Qt-Enthusiast
    an alternative to @VRonin example

    void changeColors(QTextEdit *edit){
        QString newText;
    
        QVector<QString> colors {
            "<font color=\"red\">",
            "<font color=\"green\">",
            "<font color=\"blue\">"
        };
    
        QString endFont = "</font>";
        QString ParagraphEnd = "</p>";
    
        QString text = edit->toHtml();
        auto ref = text.split(ParagraphEnd);
    
        for(int i(0); i < ref.size();i++){
            QString s = ref.at(i);
            int insert = s.lastIndexOf(">");
            s.insert(insert+1,colors.at(i%3));
            s.append(endFont+ParagraphEnd);
            newText.append(s);
        }
        edit->setHtml(newText);
    }
    

Log in to reply
 

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