Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

TextEdit - how to highlight and problem in resetting charFormat



  • I'm trying to implement a shared text editor using c++ and qt. I would like to highlight the text inserted from different users with different colors. I can do that but the problem is that than I can't reset the charFormat and all the subsequent text I wrote is hihghlighted

    VIDEO OF THE PROBLEM
    short video to demonstrate the problem

    Insert function:

    QTextCharFormat fmt;
    insertCursor.setPosition(std::stoi(pos));
    ui->textEdit->setTextCursor(insertCursor);
    ui->textEdit->insertPlainText(character.c_str());
    HighlightText(user, std::stoi(pos), std::stoi(pos) + 1);
     
    fmt.setBackground(Qt::white);
    insertCursor.setCharFormat(fmt);
    insertCursor.setPosition(std::stoi(pos) + 1, QTextCursor::MoveAnchor);
    

    HighlightText function

    void MainWindow::HighlightText(std::string user, int begin, int end){
        QTextCharFormat fmt;
        fmt.setBackground(Qt::yellow);
     
        QTextCursor cursor(ui->textEdit->document());
        cursor.setPosition(begin, QTextCursor::MoveAnchor);
        cursor.setPosition(end, QTextCursor::KeepAnchor);
        cursor.setCharFormat(fmt);
     
    }
    

    basically I'm trying to highlight only the characters inserted from another user while the text inserted directly in the textEdit should not be highlighted

    is the right way to highlight or there is a better way? and why the text I wrote directly in the text edit stay highlighted even if I set the background to white?

    thanks in advance to everyone :)


Log in to reply