我需要在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}}。
答案 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