PDA

View Full Version : QTextEdit html span order



Seddy
30th April 2013, 10:52
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):

qDebug()<<"html"<<html;
block=true;
setHtml(html);
qDebug()<<"new text"<<toPlainText();

The Output:

html "<style type="text/css">.ok{color:darkgreen;} .fail{color:darkred;} .cmd{color:darkblue;}</style>test1 test2 <span class="ok">test</span>"
new text "testtest1 test2 "

Does Anyone have an idea how this can be solved?

The complete class:

#include <QtGui/qmainwindow.h>
#include <QDebug>
#include <QtGui/qtextdocumentfragment.h>

#include "ScriptEditor2.h"
#include "ScriptInterpreter.h"

ScriptEditor2::ScriptEditor2()
{
setAcceptRichText(false);
connect(this,SIGNAL(textChanged()),this,SLOT(highl ight()));
block=false;

QMainWindow* win=new QMainWindow();
win->setCentralWidget(this);
win->show();
}

void ScriptEditor2::highlight(){
if(block) return;

QTextCursor curs=textCursor();
QString text=toPlainText();
qDebug()<<"text"<<text;
int first=curs.position();
int last=first;
while(last<text.size() && text[last]!='\n') last++;
while(first>=0 && text[first]!='\n') first--;
text.replace("\n","<br>");
QString html("<style type=\"text/css\">.ok{color:darkgreen;} .fail{color:darkred;} .cmd{color:darkblue;}</style>");

QList<QString> lines=text.split('\n');
qDebug()<<"lines"<<lines;
for(int i=0;i<lines.size();i++){
if(i>0) html.append("<br>");

QString cmd;
QList<int> errors;
QList<QString> words=lines[i].split(' ');
qDebug()<<"words"<<words;
for(int j=0;j<words.size();j++){
if(j>0) html.append(' ');

if(j==0){
if(ScriptInterpreter::commands().contains(words[j])){
html.append("<span class=\"cmd\">").append(words[j]).append("</span>");
cmd=words[j];
}else
html.append(words[j]);
}else if(j==1){
if(ScriptInterpreter::args(cmd).contains(words[j])){
html.append("<span class=\"cmd\">").append(words[j]).append("</span>");
errors=ScriptInterpreter::test(cmd,words[j],words.mid(2));
}else
html.append(words[j]);
}else{
if(errors.contains(j-2))
html.append("<span class=\"fail\">").append(words[j]).append("</span>");
else
html.append("<span class=\"ok\">").append(words[j]).append("</span>");
}
}
}

qDebug()<<"html"<<html;
block=true;
setHtml(html);
qDebug()<<"new text"<<toPlainText();
block=false;
setTextCursor(curs);
qDebug()<<"-----------------------";
}