【发布时间】:2018-06-24 18:49:59
【问题描述】:
我正在使用 Qt 的 QSyntaxHighlighter 为 QML TextEdit 中的一些类似 C 的语法着色
除了多行 cmets,一切都很好。
我以这种方式检测它们:
void highlightBlock(QString const& text) override {
bool inMultilineComment = previousBlockState() == STATES::COMMENT;
bool inSingleLineComment = false;
int previousIndex = 0;
QRegularExpression expr("(\\/\\*|\\*\\/|\\/\\/|\n)"); // will match either /**, /**, // or \n
QRegularExpressionMatchIterator it = expr.globalMatch(text);
while(it.hasNext()) {
QRegularExpressionMatch match = it.next();
const QString captured = match.captured(1);
if(captured == "/*" && !inSingleLineComment) {
inMultilineComment = true;
previousIndex = match.capturedStart(1);
}
if(captured == "*/" && inMultilineComment) {
inMultilineComment = false;
setFormat(previousIndex, match.capturedEnd(1) - previousIndex, _commentFormat);
}
if(captured == "//" && !inMultilineComment) {
inSingleLineComment = true;
}
if(captured == "\n" && inSingleLineComment) {
inSingleLineComment = false;
}
}
if(inMultilineComment) {
setFormat(previousIndex, text.size() - previousIndex, _commentFormat);
setCurrentBlockState(STATES::COMMENT);
}
else {
setCurrentBlockState(STATES::NONE);
}
}
在我使用已经着色的多行注释并在开头删除/* 之前,它一直有效。只有包含/* 的块被处理和重新着色,而不是后面的块,这意味着它们在没有注释时继续显示。
有没有简单的方法告诉 QSyntaxHighlighter 重新处理以下块以防止此类错误着色?
【问题讨论】:
标签: c++ qt syntax-highlighting