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

Code I use to highlight and change charFormat
Qt Code:
  1. fmt.setBackground(Qt::yellow);
  2. insertCursor.setPosition(std::stoi(pos));
  3. insertCursor.insertText(character.c_str(), fmt);
  4. fmt.setBackground(Qt::white);
  5. insertCursor.setCharFormat(fmt);
To copy to clipboard, switch view to plain text mode 

some images to explain better
same file opened in 2 clients
Annotazione 2020-06-17 133258.jpg
left client wrote and right client updated text with highlight
Annotazione 2020-06-17 133259.jpg
right client wrote but remain highlighted
Annotazione 2020-06-17 133260.jpg

I also tried to use 2 different cursors one with the previous charFormat and one with one highlight settings and

moving the cursor locking the anchor this way
Qt Code:
  1. fmt.setBackground(Qt::yellow);
  2.  
  3. QTextCursor cursor(ui->textEdit->document());
  4. cursor.setPosition(begin, QTextCursor::MoveAnchor);
  5. cursor.setPosition(end, QTextCursor::KeepAnchor);
  6. cursor.setCharFormat(fmt);
  7. fmt.setBackground(Qt::white);
  8. cursor.setCharFormat(fmt);
To copy to clipboard, switch view to plain text mode 
(this is a function so I pass end and begin as values)

I suppose the problem could be related to the anchor that doesn't follow anymore the cursor or the fact the cursor use the previous character charFormat when I type but I really can't find out how to solve this problem

thanks to everyone in advice