텍스트 찾기

QUiLoader 를 사용하여 .ui 파일 동적으로 로드하기.

TextFinder 예제는 라이브러리의 일부인 QUiLoader 클래스를 사용하여 .ui 파일을 동적으로 로드하고 설정하는 방법을 보여줍니다. Qt UI Tools 라이브러리에 포함되어 있습니다.

이 프로그램을 통해 사용자는 텍스트 콘텐츠 내에서 특정 단어를 찾을 수 있습니다. 사용자 인터페이스의 시각적 요소와 레이아웃은 런타임에 프로그램 리소스에서 로드됩니다.

리소스 파일 설정

이 예제에 필요한 리소스는 다음과 같습니다:

  • textfinder.ui - 다음에서 생성된 사용자 인터페이스 파일 Qt Widgets Designer
  • input.txt - 에 표시할 일부 텍스트가 포함된 텍스트 파일 QTextEdit

textfinder.ui 텍스트 파인더에 필요한 모든 QWidget 객체가 포함되어 있습니다. QLineEdit 은 사용자 입력에 사용되며, QTextEditinput.txt 의 내용을 표시하는 데 사용되며, QLabel 은 "키워드" 텍스트를 표시하는 데 사용되며, QPushButtonFind 버튼에 사용됩니다. 모든 위젯에는 합리적인 objectName 가 할당되어 있습니다. 이는 코드에서 위젯을 식별하는 데 사용됩니다.

아래 스크린샷은 다음에서 얻은 미리 보기를 보여줍니다. Qt Widgets Designer.

이 예에서는 textfinder.qrc 파일을 포함하여 애플리케이션의 실행 파일에 두 리소스를 모두 저장합니다. 또는 파일 시스템 또는 외부 바이너리 리소스 .rcc 파일에서 런타임에 파일을 로드할 수도 있습니다. 리소스 파일에 대한 자세한 내용은 Qt 리소스 시스템을 참조하십시오.

textfinder.qrc 파일에는 리소스로 포함해야 하는 모든 파일이 나열되어 있습니다:

<!DOCTYPE RCC><RCC version="1.0">
<qresource>
    <file>forms/textfinder.ui</file>
    <file>forms/input.txt</file>
</qresource>
</RCC>

런타임에 폼을 생성하기 위해 이 예제는 Qt UI Tools 라이브러리에 대해 링크됩니다. 이 작업은 textfinder.pro 파일에서 수행됩니다:

QT += widgets uitools

HEADERS = textfinder.h
SOURCES = textfinder.cpp main.cpp
RESOURCES = textfinder.qrc

TextFinder 클래스 정의

TextFinder 클래스에는 기본 사용자 인터페이스가 포함되어 있습니다. 이 클래스는 위에서 설명한 QPushButton, QTextEditQLineEdit 요소에 대한 포인터를 선언합니다. 사용자 인터페이스의 QLabel 는 코드에서 액세스할 필요가 없으므로 여기서는 선언하지 않습니다.

class TextFinder : public QWidget
{
    Q_OBJECT

public:
    explicit TextFinder(QWidget *parent = nullptr);

private slots:
    void on_findButton_clicked();

private:
    QPushButton *ui_findButton;
    QTextEdit *ui_textEdit;
    QLineEdit *ui_lineEdit;
};

on_findButton_clicked() 슬롯은 uic 에서 요구하는 자동 연결 명명 규칙에 따라 명명된 슬롯입니다.

리소스 로드

QFile 을 사용하여 런타임에 프로그램 리소스에서 데이터를 로드합니다. 이를 위한 코드는 textfinder.cpp: loadUiFileloadTextFile 의 두 가지 메서드 메서드에 있습니다.

loadUiFile 함수는 이전에 생성한 사용자 인터페이스 파일을 Qt Widgets Designer. 먼저 리소스 시스템에서 textfinder.ui 파일의 콘텐츠를 로드합니다. 그런 다음 QUiLoader 인스턴스가 생성되고 QUiLoader::load() 함수가 호출되며, 첫 번째 인수는 열린 파일이고 두 번째 인수는 부모로 설정해야 하는 위젯의 포인터입니다. 생성된 QWidget 이 반환됩니다.

static QWidget *loadUiFile(QWidget *parent)
{
    QFile file(u":/forms/textfinder.ui"_s);
    file.open(QIODevice::ReadOnly);

    QUiLoader loader;
    return loader.load(&file, parent);
}

비슷한 맥락에서 loadTextFile 함수는 리소스에서 input.txt 을 로드합니다. QTextStream::readAll () 함수를 사용하여 QTextStreamQString 으로 데이터를 읽습니다. QTextStream 은 기본적으로 현재 시스템 로캘을 사용하므로 인코딩을 UTF-8로 명시적으로 설정합니다. 마지막으로 로드된 텍스트가 반환됩니다.

static QString loadTextFile()
{
    QFile inputFile(u":/forms/input.txt"_s);
    inputFile.open(QIODevice::ReadOnly);
    QTextStream in(&inputFile);
    return in.readAll();
}

TextFinder 클래스 구현

TextFinder 클래스의 생성자는 자식 위젯을 직접 인스턴스화하지 않습니다. 대신 loadUiFile() 함수를 호출한 다음 QObject::findChild()를 사용하여 생성된 QWidget를 객체 이름으로 찾습니다.

TextFinder::TextFinder(QWidget *parent)
    : QWidget(parent)
{
    QWidget *formWidget = loadUiFile(this);

    ui_findButton = findChild<QPushButton*>("findButton");
    ui_textEdit = findChild<QTextEdit*>("textEdit");
    ui_lineEdit = findChild<QLineEdit*>("lineEdit");

그런 다음 QMetaObject::connectSlotsByName()를 사용하여 on_findButton_clicked() 슬롯의 자동 호출을 활성화합니다.

    QMetaObject::connectSlotsByName(this);

loadTextFile 함수는 QTextEdit 에 표시할 텍스트를 가져오기 위해 호출됩니다.

    ui_textEdit->setText(loadTextFile());

이제 formWidget 의 동적으로 로드된 사용자 인터페이스가 올바르게 설정되었습니다. 이제 QVBoxLayout 을 통해 formWidget 을 임베드합니다.

    auto *layout = new QVBoxLayout(this);
    layout->addWidget(formWidget);

생성자 끝에 창 제목을 설정합니다.

    setWindowTitle(tr("Text Finder"));
}

on_findButton_clicked() 함수는 ui_findButtonclicked() 신호에 연결된 슬롯입니다. searchStringui_lineEdit 에서 추출되고 documentui_textEdit 에서 추출됩니다. searchString 가 비어 있으면 QMessageBox 가 사용되어 사용자에게 단어 입력을 요청합니다. 그렇지 않으면 ui_textEdit 의 단어를 순회하고 searchString 의 모든 발생을 강조 표시합니다. 두 개의 QTextCursor 객체가 사용됩니다: 하나는 line 의 단어를 탐색하고 다른 하나는 편집 블록을 추적하는 데 사용됩니다.

void TextFinder::on_findButton_clicked()
{
    QString searchString = ui_lineEdit->text();
    QTextDocument *document = ui_textEdit->document();

    bool found = false;

    // undo previous change (if any)
    document->undo();

    if (searchString.isEmpty()) {
        QMessageBox::information(this, tr("Empty Search Field"),
                                 tr("The search field is empty. "
                                    "Please enter a word and click Find."));
    } else {
        QTextCursor highlightCursor(document);
        QTextCursor cursor(document);

        cursor.beginEditBlock();

        QTextCharFormat plainFormat(highlightCursor.charFormat());
        QTextCharFormat colorFormat = plainFormat;
        colorFormat.setForeground(Qt::red);

        while (!highlightCursor.isNull() && !highlightCursor.atEnd()) {
            highlightCursor = document->find(searchString, highlightCursor,
                                             QTextDocument::FindWholeWords);

            if (!highlightCursor.isNull()) {
                found = true;
                highlightCursor.movePosition(QTextCursor::WordRight,
                                             QTextCursor::KeepAnchor);
                highlightCursor.mergeCharFormat(colorFormat);
            }
        }

        cursor.endEditBlock();

found 플래그는 ui_textEdit 의 콘텐츠 내에서 searchString 을 찾았는지 여부를 나타내는 데 사용됩니다. 을 찾지 못하면 QMessageBox 을 사용하여 사용자에게 알립니다.

        if (found == false) {
            QMessageBox::information(this, tr("Word Not Found"),
                                     tr("Sorry, the word cannot be found."));
        }
    }
}

main() 함수

main() 함수는 TextFinder 을 인스턴스화하여 표시합니다.

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    TextFinder textFinder;
    textFinder.show();

    return app.exec();
}

폼을 애플리케이션에 포함시키는 방법에는 여러 가지가 있습니다. QUILoader를 사용하는 것도 그중 하나에 불과합니다. 사용 가능한 다른 접근 방식에 대한 자세한 내용은 애플리케이션에서 디자이너 UI 파일 사용을 참조하세요.

예제 프로젝트 @ code.qt.io

계산기 빌더도참조하세요 .

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.