Qt/C++ - Tutorial 088. Text search with highlighting in QTextEdit

QTextEdit, Qt

In connection with a small question on the forum and slightly free time today. I will answer in the form of an article on how to highlight in QTextEdit all the words that need to be found in this text.

To implement this functionality, you will need to use QSyntaxHighighter , as if writing a syntax highlighting code. Here, by the way, is an example of syntax highlighting for HTML .

And here's an example.

Search text highlight

Project structure

Search Hightlight structure

Widget

The main application window is represented by a widget.

The widget class consists of several files.

  • Widget.ui
  • Widget.h
  • Widget.cpp

I will not go into details on how to build such a window in Qt Designer, but as a result of working with Qt Designer, you get the Widget.ui file.

Widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class SearchHighLight;

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    // Slot to handle the pressing of the button to install the desired text
    void onSearchText();
    void onSearchText();

    Ui::Widget *ui;
    // Inherited class for creating syntax highlighting logic
    SearchHighLight* m_searchHighLight;
};

#endif // WIDGET_H

Widget.cpp

#include "Widget.h"
#include "ui_Widget.h"

#include "SearchHighLight.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    // Create and initialize search highlighting
    m_searchHighLight = new SearchHighLight(ui->textEdit->document());

    // We connect the signal of the button to the slots for calling the search.
    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::onSearchText);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onSearchText()
{
    // We load the text for search in syntax highlighting
    m_searchHighLight->searchText(ui->lineEdit->text());
}

SearchHightLight

And now the most interesting thing is exactly how you can highlight text in a search using QSyntaxHighligher

SearchHightLight.h

#ifndef SEARCHHIGHLIGHT_H
#define SEARCHHIGHLIGHT_H

#include <QSyntaxHighlighter>
#include <QRegularExpression>

class SearchHighLight : public QSyntaxHighlighter
{
    Q_OBJECT
    using BaseClass = QSyntaxHighlighter;
public:
    explicit SearchHighLight(QTextDocument* parent = nullptr);

    void searchText(const QString& text);

protected:
    virtual void highlightBlock(const QString &text) override;

private:
    QRegularExpression m_pattern; // Regular expression to search for, in our case, this word or text
    QTextCharFormat m_format;     // Text formatting, highlighting
};

#endif // SEARCHHIGHLIGHT_H

SearchHightLight.cpp

#include "SearchHighLight.h"

#include <QTextCharFormat>

SearchHighLight::SearchHighLight(QTextDocument* parent) : BaseClass(parent)
{
    // Set the backlight color
    m_format.setBackground(Qt::green);
}

void SearchHighLight::highlightBlock(const QString& text)
{
    // Using a regular expression, we find all matches.
    QRegularExpressionMatchIterator matchIterator = m_pattern.globalMatch(text);
    while (matchIterator.hasNext())
    {
        // Highlight all matches
        QRegularExpressionMatch match = matchIterator.next();
        setFormat(match.capturedStart(), match.capturedLength(), m_format);
    }
}

void SearchHighLight::searchText(const QString& text)
{
    // Set the text as a regular expression.
    m_pattern = QRegularExpression(text);
    rehighlight(); // Restart the backlight
}

Conclusion

And as a conclusion, a link to the Git repository with this example.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

DP
Oct. 19, 2019, 1:45 a.m.
Dmitrij Pasynkov

C++ - Test 001. The first program and data types

  • Result:26points,
  • Rating points-10
AS
Oct. 18, 2019, 1:27 p.m.
Artem Sergeevich

C++ - Test 001. The first program and data types

  • Result:13points,
  • Rating points-10
MB
Oct. 18, 2019, 11:05 a.m.
Mihail Bulatov

C++ - Test 001. The first program and data types

  • Result:86points,
  • Rating points6
Last comments
Oct. 17, 2019, 2:17 a.m.
Evgenij Legotskoj

Используем, там где требуется :)
MP
Oct. 17, 2019, 2:15 a.m.
Mikhail Petrov

Совет: подключайте ресурсы динамически. Используйте Resource Compiler: https://doc.qt.io/qt-5/rcc.html
Oct. 16, 2019, 6:45 a.m.
Evgenij Legotskoj

Если это не чистой воды спам, а по делу, то без проблем. Но в таком случае лучше создавайте отдельный вопрос на форуме . При создании вопроса есть поле, в котором можно указать статью…
KK
Oct. 16, 2019, 6:39 a.m.
Kirill Kirilych

А тут можно ссылки на сторонний ресурс показывать? Нашёл на habr похожую статью, только там чуток отличается код и про локальный сервер написано, нужно чтоб кто то понимающий посмотрел и своё …
Now discuss on the forum
Oct. 18, 2019, 1:30 p.m.
Evgenij Legotskoj

Добрый день. У вас там пробелы находятся в тексте, поэтому и не может сконвертировать. фукция map применяет float ко все символам в каждой строке. В том числе и к символам пробела. А пробе…
Oct. 17, 2019, 10:31 a.m.
Ruslan Volshebnik

Я вас понял) Спасибо ещё раз. Вы помогли мне во всём разобраться.
t
Oct. 17, 2019, 4:13 a.m.
tupo_chel

И тебе спасибо за помощь)
Oct. 17, 2019, 2:14 a.m.
Evgenij Legotskoj

Добрый день. Ну да, этот вариант жизнеспособен. Есть только один момент, который вам необходимо понимать в данном случае. И чего в этой статье или нет, или сказано как-то совсем вскользь, …
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB