CroCo
CroCo

Reputation: 5741

Typing is messy if I use html with QTextEdit

I'm trying to change the attributes of single words such font and color. QTextEdit allows me to set the text as html via setHtml(htmlText), after setting QString as html, typing becomes messy. I can't type spaces nor hit enter. Sometimes words are written backward.

void MainWindow::on_textEdit_textChanged()
{
    QString plainText = ui->textEdit->toPlainText();
    QString htmlText = "<font color='red'>" + plainText + "</font>";

    disconnect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(on_textEdit_textChanged()));

    ui->textEdit->setHtml(htmlText);
    QTextCursor cursor(ui->textEdit->textCursor());
    cursor.movePosition(QTextCursor::EndOfWord);
    ui->textEdit->setTextCursor(cursor);

    connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(on_textEdit_textChanged()));
}

The color is set correctly but typing is inconsistent. I'm not expert in html. Any suggestions.

Upvotes: 1

Views: 53

Answers (1)

HTML is a transfer representation for the syntax tree of the document. You need to be modifying one or the other, otherwise you'll face the fallout from interactions between the two. Choose one and stick to it.

Since you're using the QTextDocument interface, you should be making all changes using that interface. There's no need to deal with HTML directly then. To change attributes of a chunk of text, select the text, then manipulate it via the cursor API.

Upvotes: 2

Related Questions