重载QSyntaxHighlighter的highlightBlock
void MyHighlighter::highlightBlock(const QString &text)
{
QTextCharFormat myClassFormat;
myClassFormat.setFontWeight(QFont::Bold);
myClassFormat.setForeground(Qt::darkMagenta);
QString pattern = "\\bMy[A-Za-z]+\\b";
QRegExp expression(pattern);
int index = text.indexOf(expression);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, myClassFormat);
index = text.indexOf(expression, index + length);
}
}
调用方式:
QTextEdit *editor = new QTextEdit;
MyHighlighter *highlighter = new MyHighlighter(editor->document());
本文介绍了如何在QTextEdit中自定义QSyntaxHighlighter,通过highlightBlock函数实现对含有My开头单词的文本进行粗体并设置暗洋红前景色的高亮。方法涉及创建QTextCharFormat、QRegExp和使用indexOf与setFormat进行匹配和格式设置。
1377

被折叠的 条评论
为什么被折叠?



