Evgenii Legotckoi
Жел. 14, 2018, 3:13 Т.Ж.

Qt/C++ - Оқулық 088. QTextEdit виджетінде ерекшеленген мәтінді табу

Осыған байланысты форумда шағын сұрақ және бүгінгі бос уақыт. Мен QTextEdit бағдарламасында осы мәтіннен табу қажет барлық сөздерді қалай таңдауға болатыны туралы мақала түрінде жауап беремін.

Бұл функцияны іске асыру үшін сізге синтаксисті бөлектеу кодын жазып жатқандай QSyntaxHighighter пайдалану қажет болады. Айтпақшы, мұнда HTML үшін синтаксисті бөлектеу мысалы келтірілген.

Ал мына бір мысал.

Іздеудегі мәтінді бөлектеңіз


Жоба құрылымы

Search Hightlight құрылымы

Виджет

Негізгі қолданба терезесі виджет арқылы ұсынылған.

Виджет класы бірнеше файлдардан тұрады.

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

Мен Qt Designer бағдарламасында мұндай терезені қалай құруға болатынын егжей-тегжейлі қарастырмаймын, бірақ Qt Designer-пен жұмыс істеу нәтижесінде сіз Widget.ui файлын аласыз.

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());
}

HighLight іздеу

Енді ең қызығы, 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
}

Қорытынды

Соңында, осы мысалмен Git репозиторийіне сілтеме.

Осы тақырып бойынша ұсынылатын мақалалар

Мақала бойынша сұралады0сұрақтар(лар)

2

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

Пікірлер

Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
Кіріңіз немесе Тіркеліңіз