的QTextEdit。在textChanged插槽中更改某些单词的颜色并恢复

时间:2014-07-26 13:53:45

标签: qt qtextedit

我需要在QTextEdit中用其他颜色绘制一些单词。

void Wnd::onTextChanged()
{
    QString s = ui->textEdit->toPlainText();
    s = addColors(s);

    ui->textEdit->blockSignals(true);
    ui->textEdit->setHtml(s);
    ui->textEdit->blockSignals(false);
}

QTextEditor::setHtml在开头设置光标和可见区域。但我需要使用QTextEdit使用与QTextEdit使用简单的<{1}}。

1 个答案:

答案 0 :(得分:2)

你做错了,造成了很大的开销。你应该这样做:

void Wnd::onTextChanged()
{
    QTextDocument *doc = ui->textEdit->document();

    // clears old formating
    QTextCursor cursor(doc);
    cursor.select(QTextCursor::Document);
    cursor.setCharFormat(QTextCharFormat());

    Q_FOREACH(QString word, wordsToColor) {
        QTextCursor cursor = doc->find(word);

        while(cursor.hasSelection()) {
             cursor.setCharFormat(someTextCharFormat);
             cursor = doc->find(word, cursor); // next word
        }
    }
}

您也可能尝试执行已经解决的问题:http://qt-project.org/doc/qt-4.8/richtext-syntaxhighlighter.html