I edited it like this. But all text is not printed in textEdit even though the word is added to the correct position and colored.

ui->textEdit->setText(display_text);

QTextcursor cursor=ui->textEdit->textCursor();
cursor.movePosition(QTextCursor::Right,QTextCursor::MoveAnchor,cursor_position);
cursor.insertHtml("<span style=color:red;>"+coloring_string+"</span>");
ui->textEdit->setTextCursor(cursor);
1

There are 1 best solutions below

3
eyllanesc On

You have to use setExtraSelections:

#include <QApplication>
#include <QTextEdit>

class Editor: public QTextEdit {
public:
    Editor(QWidget *parent=nullptr): QTextEdit(parent){
        connect(this, &QTextEdit::cursorPositionChanged, this, &Editor::highlightCurrentLine);
        highlightCurrentLine();
    }
private:
    void highlightCurrentLine(){
        QList<QTextEdit::ExtraSelection> extraSelections;
        if (!isReadOnly()) {
            QTextEdit::ExtraSelection selection;
            QColor lineColor("red");
            selection.format.setBackground(lineColor);
            selection.format.setProperty(QTextFormat::FullWidthSelection, true);
            selection.cursor = textCursor();
            selection.cursor.clearSelection();
            extraSelections.append(selection);
        }
        setExtraSelections(extraSelections);
    }
};
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setStyle("fusion");
    Editor editor;
    editor.resize(640, 480);
    editor.show();
    return a.exec();
}