好吧,经过一些实验后,我将 Qt Creator 的一些代码操纵成有用的东西,您可以在 QSyntaxHighlighter 派生类中直接使用。如果您不想在文档中使用任何其他默认前景色和背景色,请跳过带有 tempCursor.setCharFormat() 和 blockFormat.setBackground() 的部分。这工作得很好,所以试试看。
void MyHighlighter::asHtml(QString& html)
{
// Create a new document from all the selected text document.
QTextCursor cursor(document());
cursor.select(QTextCursor::Document);
QTextDocument* tempDocument(new QTextDocument);
Q_ASSERT(tempDocument);
QTextCursor tempCursor(tempDocument);
tempCursor.insertFragment(cursor.selection());
tempCursor.select(QTextCursor::Document);
// Set the default foreground for the inserted characters.
QTextCharFormat textfmt = tempCursor.charFormat();
textfmt.setForeground(Qt::gray);
tempCursor.setCharFormat(textfmt);
// Apply the additional formats set by the syntax highlighter
QTextBlock start = document()->findBlock(cursor.selectionStart());
QTextBlock end = document()->findBlock(cursor.selectionEnd());
end = end.next();
const int selectionStart = cursor.selectionStart();
const int endOfDocument = tempDocument->characterCount() - 1;
for(QTextBlock current = start; current.isValid() and current not_eq end; current = current.next()) {
const QTextLayout* layout(current.layout());
foreach(const QTextLayout::FormatRange &range, layout->additionalFormats()) {
const int start = current.position() + range.start - selectionStart;
const int end = start + range.length;
if(end <= 0 or start >= endOfDocument)
continue;
tempCursor.setPosition(qMax(start, 0));
tempCursor.setPosition(qMin(end, endOfDocument), QTextCursor::KeepAnchor);
tempCursor.setCharFormat(range.format);
}
}
// Reset the user states since they are not interesting
for(QTextBlock block = tempDocument->begin(); block.isValid(); block = block.next())
block.setUserState(-1);
// Make sure the text appears pre-formatted, and set the background we want.
tempCursor.select(QTextCursor::Document);
QTextBlockFormat blockFormat = tempCursor.blockFormat();
blockFormat.setNonBreakableLines(true);
blockFormat.setBackground(Qt::black);
tempCursor.setBlockFormat(blockFormat);
// Finally retreive the syntax higlighted and formatted html.
html = tempCursor.selection().toHtml();
delete tempDocument;
} // asHtml