文本高亮
对于textedit里录入的部分单词我们可以实现高亮,实现高亮主要依赖于QSyntaxHighlighter。
我们先创建一个Qt Application类,类名MainWindow, 然后新增一个C++类,类名为MySyntaxHighlighter。
#ifndef MYSYNTAXHIGHLIGHTER_H
#define MYSYNTAXHIGHLIGHTER_H
#include <QSyntaxHighlighter>
#include <QTextDocument>
class MySyntaxHighlighter:public QSyntaxHighlighter
{
Q_OBJECT
public:
explicit MySyntaxHighlighter(QTextDocument* parent = 0);
//重写实现高亮
protected:
void highlightBlock(const QString& text);
};
#endif // MYSYNTAXHIGHLIGHTER_H
这个类声明了highlightBlock函数,这是一个虚函数继承自QSyntaxHighlighter。每次我们录入文字时,会自动调用这个函数。下面实现MySyntaxHighlighter类
#include "mysyntaxhighlighter.h"
#include <QFont>
MySyntaxHighlighter::MySyntaxHighlighter(QTextDocument* parent):QSyntaxHighlighter (parent)
{
}
void MySyntaxHighlighter::highlightBlock(const QString &text)
{
QTextCharFormat myFormat;
myFormat.setFont(QFont("微软雅黑"));
myFormat.setFontWeight(QFont::Bold);
myFormat.setForeground(Qt::green);
//匹配char
QString pattern = "\\bchar\\b";
//创建正则表达式
QRegExp express(pattern);
//从索引0的位置开始匹配
int index = text.indexOf(express);
while (index>0) {
int matchLen = express.matchedLength();
//对匹配的字符串设置高亮
setFormat(index, matchLen, myFormat);
index = text.indexOf(express, index+matchLen);
}
}
在highlightBlock函数中,我们实现了一个高亮的文字模式,当录入的字符串包含char时,char会被高亮。
我们在mainwindow.ui中添加一个textedit,然后在mainwindow的构造函数中添加我们刚才编写的高亮模块。
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_ligher = new MySyntaxHighlighter(ui->textEdit->document());
}
程序运行后,在编辑器中输入hello char,会看到char高亮了
实现代码编辑器
Qt 的案例中有提供过文本高亮和显示行号的demo,我把它整理起来了。
我们先声明codeeditor类,以及行号显示的类
#ifndef CODEEDITOR_H
#define CODEEDITOR_H
#include <QPlainTextEdit>
QT_BEGIN_NAMESPACE
class QPaintEvent;
class QResizeEvent;
class QSize;
class QWidget;
QT_END_NAMESPACE
class LineNumberArea;
class CodeEditor : public QPlainTextEdit
{
Q_OBJECT
public:
CodeEditor(QWidget *parent = nullptr);
void lineNumberAreaPaintEvent(QPaintEvent *event);
int lineNumberAreaWidth();
protected:
void resizeEvent(QResizeEvent *event) override;
private slots:
void updateLineNumberAreaWidth(int newBlockCount);
void highlightCurrentLine();
void updateLineNumberArea(const QRect &rect, int dy);
private:
QWidget *lineNumberArea;
};
class LineNumberArea : public QWidget
{
public:
LineNumberArea(CodeEditor *editor) : <