参考QT官网提供的语法高亮示例,我尝试在我的应用程序中实现(可以称之为复制粘贴)多行注释相同的逻辑。下面是多行注释高亮的代码:
在构造函数内:
quotationFormat.setForeground(QColor(164, 14, 14));
rule.pattern = QRegExp("\".*\"");
rule.format = quotationFormat;
highlightingRules.append(rule);
charFormat.setForeground(QColor(164, 14, 14));
rule.pattern = QRegExp("\'.*\'");
rule.format = charFormat;
highlightingRules.append(rule);
singleLineCommentFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
multiLineCommentFormat.setForeground(Qt::darkGreen);
commentStartExpression = QRegExp("/\\*");
commentEndExpression = QRegExp("\\*/");
在highlightBlock()函数内部:
foreach (const HighlightingRule &rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = commentStartExpression.indexIn(text);
while (startIndex >= 0) {
int endIndex = commentEndExpression.indexIn(text, startIndex);
int commentLength;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex
+ commentEndExpression.matchedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = commentStartExpression.indexIn(text, startIndex + commentLength);
}
但是我仍然遇到了一个问题,当/*出现在引号内时。它会以多行注释的颜色(绿色)一直持续到最后(/*.png" ] }
)请参考以下示例文档内容:
{
"code": [
"./Code/Main.js"
],
"textures": [
"./Content/*.png"
]
}
我不是正则表达式的专家,但我猜测这个正则表达式有问题。