I have the simplest minimum working example to highlight just two lines. The two lines to be highlighted are shown below. These two lines are the only contents of the QTextEdit.
begin
end
Using QSyntaxHighlighter and QTextEdit, I am unable to highlight these two lines using QRegularExpression. The working code is shown below. When compiled using QtCreater, it gives zero warnings and runs fine. I am using Qt5.13 MinGW x64. The interesting point is that the RegEx I am using works fine in online checker like https://regex101.com/.
Ultimately I want to see that the two lines should appear in red color. The first line contains the word "begin" and the second line contains the word "end".* Please help.
mySyntaxHighlighter.h
class mySyntaxHighlighter : public QSyntaxHighlighter
{
Q_OBJECT
public:
explicit mySyntaxHighlighter(QTextDocument *document);
signals:
public slots:
protected:
void highlightBlock(const QString &text);
};
mySyntaxHighligher.cpp
#include "mysyntaxhighlighter.h"
mySyntaxHighlighter::mySyntaxHighlighter(QTextDocument *document) : QSyntaxHighlighter(document)
{
}
void mySyntaxHighlighter::highlightBlock(const QString &text) {
QTextCharFormat citeFormat;
citeFormat.setForeground(QColor(Qt::red));
citeFormat.setFontFamily("Consolas");
citeFormat.setFontPointSize(14);
QRegularExpression regex = QRegularExpression(QStringLiteral("begin(.*\n)+end"));
regex.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
QRegularExpressionMatchIterator i = regex.globalMatch(text);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
setFormat(match.capturedStart(), match.capturedLength(), citeFormat);
}
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mysyntaxhighlighter.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTextEdit *te = new QTextEdit(this);
te->setAcceptRichText(false);
te->setFontFamily("Consolas");
te->setFontPointSize(14);
te->setMinimumSize(1200, 600);
myHighlighter = new mySyntaxHighlighter(te->document());
setCentralWidget(te);
setMinimumWidth(1200);
te->setFocus();
}
mainwindow.h
#include <QMainWindow>
#include <QTextEdit>
#include "mysyntaxhighlighter.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
mySyntaxHighlighter *myHighlighter;
};