Qt写代码时特定词不变色
要让Qt中的特定词不变色,你可以使用QSyntaxHighlighter类来自定义语法高亮器。以下是一个简单的示例,将"特定词"不变色:
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
class CustomHighlighter : public QSyntaxHighlighter
{
public:
CustomHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
// 定义特定词的格式
QTextCharFormat format;
format.setForeground(Qt::black); // 设置前景色为黑色
format.setFontWeight(QFont::Bold); // 设置字体为粗体
// 添加需要着色的特定词
QStringList words;
words << "特定词1" << "特定词2" << "特定词3";
// 构建正则表达式
QString pattern = "\\b(" + words.join("|") + ")\\b";
// 编译正则表达式
m_pattern = QRegExp(pattern);
// 设置特定词的格式
m_format = format;
}
protected:
void highlightBlock(const QString &text) override
{
// 使用正则表达式匹配特定词
int index = text.indexOf(m_pattern);
while (index >= 0)
{
int length = m_pattern.matchedLength();
setFormat(index, length, m_format); // 应用格式
index = text.indexOf(m_pattern, index + length);
}
}
private:
QRegExp m_pattern;
QTextCharFormat m_format;
};
要使用此自定义语法高亮器,你可以将其附加到你的文本编辑器中:
QTextEdit *editor = new QTextEdit(this);
CustomHighlighter *highlighter = new CustomHighlighter(editor->document());
这样,"特定词"将以黑色粗体显示,并且不会被其他语法高亮器改变颜色
原文地址: https://www.cveoy.top/t/topic/iBes 著作权归作者所有。请勿转载和采集!