{/'title/':/'Qt代码高亮:如何让特定词不变色?/',/'description/':/'本文介绍如何使用Qt的QSyntaxHighlighter类自定义语法高亮器,让代码中的特定词不变色。示例代码展示了如何匹配特定词并设置其格式为黑色粗体。/',/'keywords/':/'Qt, 语法高亮, QSyntaxHighlighter, 代码着色, 特定词, 不变色, 自定义/',/'content/':/'要让Qt中的特定词不变色,你可以使用QSyntaxHighlighter类来自定义语法高亮器。以下是一个简单的示例,将///'特定词///'不变色://n//ncpp//n#include <QSyntaxHighlighter>//n#include <QTextCharFormat>//n//nclass CustomHighlighter : public QSyntaxHighlighter//n{//npublic://n CustomHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)//n {//n // 定义特定词的格式//n QTextCharFormat format;//n format.setForeground(Qt::black); // 设置前景色为黑色//n format.setFontWeight(QFont::Bold); // 设置字体为粗体//n//n // 添加需要着色的特定词//n QStringList words;//n words << ///'特定词1///' << ///'特定词2///' << ///'特定词3///';//n//n // 构建正则表达式//n QString pattern = ///'//b(///' + words.join(///'|///') + ///'//)//b///';//n//n // 编译正则表达式//n m_pattern = QRegExp(pattern);//n//n // 设置特定词的格式//n m_format = format;//n }//n//nprotected://n void highlightBlock(const QString &text) override//n {//n // 使用正则表达式匹配特定词//n int index = text.indexOf(m_pattern);//n while (index >= 0)//n {//n int length = m_pattern.matchedLength();//n setFormat(index, length, m_format); // 应用格式//n index = text.indexOf(m_pattern, index + length);//n }//n }//n//nprivate://n QRegExp m_pattern;//n QTextCharFormat m_format;//n};//n//n//n要使用此自定义语法高亮器,你可以将其附加到你的文本编辑器中://n//ncpp//nQTextEdit *editor = new QTextEdit(this);//nCustomHighlighter *highlighter = new CustomHighlighter(editor->document());//n//n//n这样,///'特定词///'将以黑色粗体显示,并且不会被其他语法高亮器改变颜色。/

Qt代码高亮:如何让特定词不变色?