高亮关键词的需求不一样,可能采用的比较适合的方法也不一样,以下对常见方法作小结。
1 QSyntaxHighlighter
QSyntaxHighlighter用于高亮QTextDocument中的text,要求继承QSyntaxHighlighter并实现highlightBlock
virtual void highlightBlock(const QString &text) = 0;
下面给出示例代码:
//.h
#ifndef HIGHLIGHTER_H #define HIGHLIGHTER_H #include <QSyntaxHighlighter> class Highlighter : public QSyntaxHighlighter { public: Highlighter(QObject* pParent = 0): QSyntaxHighlighter(pParent){} void setColorText(const QString& strText, const QColor& color); protected: virtual void highlightBlock(const QString& strText); private: QRegExp pattern; QTextCharFormat format; }; #endif // HIGHLIGHTER_H
//.cpp
#include "Highlighter.h" void Highlighter::setColorText(const QString& strText, const QColor& color) { pattern = QRegExp(strText); format.setForeground(color); } void Highlighter::highlightBlock(const QString& strText) { QRegExp expression(pattern); int iIndex = strText.indexOf(expression); while (iIndex >= 0) { int iLength = expression.matchedLength(); setFormat(iIndex, iLength, format); iIndex = strText.indexOf(expression, iIndex + iLength); } }
//main
pHighlighter = new Highlighter(ui.textEdit); pHighlighter->setColorText("hello world", QColor("red"));
//效果
未完待续...
原文地址:https://www.cnblogs.com/fengyaoyao/p/12491746.html
时间: 2024-10-29 17:15:48