Evgenii Legotckoi
Dec. 14, 2018, 3:13 a.m.

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

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

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. class SearchHighLight;
  7.  
  8. namespace Ui {
  9. class Widget;
  10. }
  11.  
  12. class Widget : public QWidget
  13. {
  14. Q_OBJECT
  15.  
  16. public:
  17. explicit Widget(QWidget *parent = nullptr);
  18. ~Widget();
  19.  
  20. private:
  21. // Slot to handle the pressing of the button to install the desired text
  22. void onSearchText();
  23. void onSearchText();
  24.  
  25. Ui::Widget *ui;
  26. // Inherited class for creating syntax highlighting logic
  27. SearchHighLight* m_searchHighLight;
  28. };
  29.  
  30. #endif // WIDGET_H

Widget.cpp

  1. #include "Widget.h"
  2. #include "ui_Widget.h"
  3.  
  4. #include "SearchHighLight.h"
  5.  
  6. Widget::Widget(QWidget *parent) :
  7. QWidget(parent),
  8. ui(new Ui::Widget)
  9. {
  10. ui->setupUi(this);
  11. // Create and initialize search highlighting
  12. m_searchHighLight = new SearchHighLight(ui->textEdit->document());
  13.  
  14. // We connect the signal of the button to the slots for calling the search.
  15. connect(ui->pushButton, &QPushButton::clicked, this, &Widget::onSearchText);
  16. }
  17.  
  18. Widget::~Widget()
  19. {
  20. delete ui;
  21. }
  22.  
  23. void Widget::onSearchText()
  24. {
  25. // We load the text for search in syntax highlighting
  26. m_searchHighLight->searchText(ui->lineEdit->text());
  27. }

SearchHightLight

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

SearchHightLight.h

  1. #ifndef SEARCHHIGHLIGHT_H
  2. #define SEARCHHIGHLIGHT_H
  3.  
  4. #include <QSyntaxHighlighter>
  5. #include <QRegularExpression>
  6.  
  7. class SearchHighLight : public QSyntaxHighlighter
  8. {
  9. Q_OBJECT
  10. using BaseClass = QSyntaxHighlighter;
  11. public:
  12. explicit SearchHighLight(QTextDocument* parent = nullptr);
  13.  
  14. void searchText(const QString& text);
  15.  
  16. protected:
  17. virtual void highlightBlock(const QString &text) override;
  18.  
  19. private:
  20. QRegularExpression m_pattern; // Regular expression to search for, in our case, this word or text
  21. QTextCharFormat m_format; // Text formatting, highlighting
  22. };
  23.  
  24. #endif // SEARCHHIGHLIGHT_H

SearchHightLight.cpp

  1. #include "SearchHighLight.h"
  2.  
  3. #include <QTextCharFormat>
  4.  
  5. SearchHighLight::SearchHighLight(QTextDocument* parent) : BaseClass(parent)
  6. {
  7. // Set the backlight color
  8. m_format.setBackground(Qt::green);
  9. }
  10.  
  11. void SearchHighLight::highlightBlock(const QString& text)
  12. {
  13. // Using a regular expression, we find all matches.
  14. QRegularExpressionMatchIterator matchIterator = m_pattern.globalMatch(text);
  15. while (matchIterator.hasNext())
  16. {
  17. // Highlight all matches
  18. QRegularExpressionMatch match = matchIterator.next();
  19. setFormat(match.capturedStart(), match.capturedLength(), m_format);
  20. }
  21. }
  22.  
  23. void SearchHighLight::searchText(const QString& text)
  24. {
  25. // Set the text as a regular expression.
  26. m_pattern = QRegularExpression(text);
  27. rehighlight(); // Restart the backlight
  28. }

Conclusion

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

Recommended articles on this topic

By article asked0question(s)

2

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup