さて、いくつかの実験の後、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