I'm having a problem with inserting html into a QTextEdit.
Sometimes when I insert text with multiple spans, the order of the spans gets inverted.

Part of the code (on a QTextEdit object):
Qt Code:
  1. qDebug()<<"html"<<html;
  2. block=true;
  3. setHtml(html);
  4. qDebug()<<"new text"<<toPlainText();
To copy to clipboard, switch view to plain text mode 

The Output:
Qt Code:
  1. html "<style type="text/css">.ok{color:darkgreen;} .fail{color:darkred;} .cmd{color:darkblue;}</style>test1 test2 <span class="ok">test</span>"
  2. new text "testtest1 test2 "
To copy to clipboard, switch view to plain text mode 

Does Anyone have an idea how this can be solved?

The complete class:
Qt Code:
  1. #include <QtGui/qmainwindow.h>
  2. #include <QDebug>
  3. #include <QtGui/qtextdocumentfragment.h>
  4.  
  5. #include "ScriptEditor2.h"
  6. #include "ScriptInterpreter.h"
  7.  
  8. ScriptEditor2::ScriptEditor2()
  9. {
  10. setAcceptRichText(false);
  11. connect(this,SIGNAL(textChanged()),this,SLOT(highlight()));
  12. block=false;
  13.  
  14. win->setCentralWidget(this);
  15. win->show();
  16. }
  17.  
  18. void ScriptEditor2::highlight(){
  19. if(block) return;
  20.  
  21. QTextCursor curs=textCursor();
  22. QString text=toPlainText();
  23. qDebug()<<"text"<<text;
  24. int first=curs.position();
  25. int last=first;
  26. while(last<text.size() && text[last]!='\n') last++;
  27. while(first>=0 && text[first]!='\n') first--;
  28. text.replace("\n","<br>");
  29. QString html("<style type=\"text/css\">.ok{color:darkgreen;} .fail{color:darkred;} .cmd{color:darkblue;}</style>");
  30.  
  31. QList<QString> lines=text.split('\n');
  32. qDebug()<<"lines"<<lines;
  33. for(int i=0;i<lines.size();i++){
  34. if(i>0) html.append("<br>");
  35.  
  36. QString cmd;
  37. QList<int> errors;
  38. QList<QString> words=lines[i].split(' ');
  39. qDebug()<<"words"<<words;
  40. for(int j=0;j<words.size();j++){
  41. if(j>0) html.append(' ');
  42.  
  43. if(j==0){
  44. if(ScriptInterpreter::commands().contains(words[j])){
  45. html.append("<span class=\"cmd\">").append(words[j]).append("</span>");
  46. cmd=words[j];
  47. }else
  48. html.append(words[j]);
  49. }else if(j==1){
  50. if(ScriptInterpreter::args(cmd).contains(words[j])){
  51. html.append("<span class=\"cmd\">").append(words[j]).append("</span>");
  52. errors=ScriptInterpreter::test(cmd,words[j],words.mid(2));
  53. }else
  54. html.append(words[j]);
  55. }else{
  56. if(errors.contains(j-2))
  57. html.append("<span class=\"fail\">").append(words[j]).append("</span>");
  58. else
  59. html.append("<span class=\"ok\">").append(words[j]).append("</span>");
  60. }
  61. }
  62. }
  63.  
  64. qDebug()<<"html"<<html;
  65. block=true;
  66. setHtml(html);
  67. qDebug()<<"new text"<<toPlainText();
  68. block=false;
  69. setTextCursor(curs);
  70. qDebug()<<"-----------------------";
  71. }
To copy to clipboard, switch view to plain text mode