이 페이지에서

텍스트 찾기

QUiLoader 를 사용하여 .ui 파일을 동적으로 불러오기.

TextFinder 예제는 QUiLoader 클래스를 사용하여 .ui 파일을 동적으로 불러오고 설정하는 방법을 보여줍니다. 이 클래스는 Qt UI Tools 라이브러리에 포함된 xml-ph-0001@deepl.internal 클래스를 사용하여 .ui 파일을 동적으로 로드하고 설정하는 방법을 보여줍니다.

이 프로그램은 사용자가 텍스트 내용 내에서 특정 단어를 검색할 수 있도록 합니다. 사용자 인터페이스의 시각적 요소와 레이아웃은 실행 시 프로그램 리소스에서 불러옵니다.

TextFinder의 찾기 버튼 및 입력란TextFinder 강조 표시된 결과

리소스 파일 설정

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

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

textfinder.ui 에는 ‘Text Finder’에 필요한 모든 ‘ QWidget ’ 객체가 포함되어 있습니다. 사용자 입력을 위해 ‘ QLineEdit ’가 사용되며, ‘ input.txt ’의 내용을 표시하기 위해 ‘ QTextEdit ’가, “Keyword”라는 텍스트를 표시하기 위해 ‘ QLabel ’가, ‘ Find ’ 버튼을 위해 ‘ QPushButton ’가 사용됩니다. 모든 위젯에는 적절한 ‘ objectName ’가 할당되어 있다는 점에 유의하십시오. 이 값들은 코드에서 해당 위젯을 식별하는 데 사용됩니다.

아래 스크린샷은 Qt Widgets Designer에서 얻은 미리보기 화면입니다.

TestFinder 사용자 인터페이스(UI) 스크린샷

이 예제에서는 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, QTextEdit 및 QLineEdit 요소에 대한 포인터를 선언합니다. 사용자 인터페이스의 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 에서 요구하는 자동 연결(Automatic Connection) 명명 규칙에 따라 이름이 지정된 슬롯입니다.

리소스 불러오기

우리는 런타임에 프로그램 리소스에서 데이터를 불러오기 위해 ` QFile `를 사용합니다. 이에 대한 코드는 ` textfinder.cpp` 상단에 있는 두 가지 메서드, 즉 ` loadUiFile `와 ` loadTextFile`에 있습니다.

loadUiFile 함수는 앞서 생성된 사용자 인터페이스 파일을 불러옵니다 Qt Widgets Designer. 먼저, 리소스 시스템에서 textfinder.ui 파일을 찾아 엽니다. 그런 다음 QUiLoader 인스턴스를 생성하고, QUiLoader::load() 함수를 호출합니다. 이때 첫 번째 인수는 열린 파일이고, 두 번째 인수는 부모로 설정해야 할 위젯의 포인터입니다. 생성된 QWidget 객체가 반환됩니다.

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

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

이와 유사하게, loadTextFile 함수는 리소스에서 input.txt 파일을 찾아 열어줍니다. 그런 다음 QTextStream::readAll() 함수를 사용하여 파일의 내용을 반환합니다.

static QString loadTextFile()
{
    QFile inputFile(u":/forms/input.txt"_s);
    if (!inputFile.open(QIODevice::ReadOnly))
        qFatal("Cannot open resource file");

   return QTextStream(&inputFile).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_findButton 의 clicked() 신호에 연결된 슬롯입니다. searchString 는 ui_lineEdit 에서 추출되며, document 는 ui_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 플래그는 searchString 가 ui_textEdit 의 내용 내에서 발견되었는지 여부를 나타내는 데 사용됩니다. 발견되지 않은 경우, 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 `을 사용하는 것은 그중 하나일 뿐입니다. 사용 가능한 다른 방법에 대한 자세한 내용은 ‘애플리케이션에서 Qt Widgets Designer UI 파일 사용하기’를 참조하십시오.

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

‘Calculator Builder’항목도 참조하십시오 .

© 2026 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.