계산기 빌더
런타임에 Qt Widgets Designer 양식에서 사용자 인터페이스 만들기.
계산기 양식 예제에서 만든 양식을 사용하여 애플리케이션이 실행될 때 동일한 사용자 인터페이스가 생성되거나 애플리케이션이 빌드될 때 정의될 수 있음을 보여줍니다.
준비
계산기 양식 예제에서는 수정 없이 사용할 수 있는 사용자 인터페이스를 정의합니다. 이 예에서는 리소스 파일을 사용하여 이전 예제에서 만든 calculatorform.ui
파일을 포함하지만, 이 파일을 디스크에 저장할 수도 있습니다.
런타임에 양식을 생성하려면 예제를 QtUiTools
모듈 라이브러리에 연결해야 합니다. 우리가 사용하는 프로젝트 파일에는 이 작업을 수행하는 데 필요한 모든 정보가 포함되어 있습니다:
target_link_libraries(calculatorbuilder PUBLIC Qt::Core Qt::Gui Qt::UiTools Qt::Widgets )
UI 파일은 리소스에서 로드됩니다:
set(calculatorbuilder_resource_files "calculatorform.ui" )
qmake
:
RESOURCES = calculatorbuilder.qrc SOURCES = main.cpp QT += widgets uitools
다른 모든 필요한 파일은 평소와 같이 선언됩니다.
계산기 양식 로드하기
libQtUiTools
라이브러리에서 제공하는 QUiLoader 클래스를 사용해야 하므로 먼저 모듈의 헤더 파일을 포함해야 합니다:
#include <QtUiTools>
최상위 위젯을 생성하고 예제의 리소스에서 QFile 객체를 통해 검색한 사용자 인터페이스를 로드하는 정적 헬퍼 함수를 만듭니다:
static QWidget *loadCalculatorForm(QWidget *parent = nullptr) { QUiLoader loader; QFile file(u":/forms/calculatorform.ui"_s); if (!file.open(QFile::ReadOnly)) return nullptr; QWidget *formWidget = loader.load(&file, parent); file.close(); if (formWidget == nullptr) return nullptr;
예제의 리소스에 사용자 인터페이스를 포함시킴으로써 예제가 실행될 때 사용자 인터페이스가 표시되도록 합니다. loader.load()
함수는 파일에 포함된 사용자 인터페이스 설명을 가져와 CalculatorForm
의 하위 위젯으로 양식 위젯을 구성합니다.
생성된 사용자 인터페이스에는 스핀 박스 2개와 레이블 1개 등 세 개의 위젯이 있습니다. 편의를 위해 FormBuilder
에 의해 구성된 위젯에서 이러한 위젯에 대한 포인터를 검색하고 나중에 사용할 수 있도록 기록합니다. findChild()
템플릿 함수를 사용하면 위젯을 쿼리하여 명명된 하위 위젯을 찾을 수 있습니다.
auto *inputSpinBox1 = formWidget->findChild<QSpinBox*>(u"inputSpinBox1"_s); auto *inputSpinBox2 = formWidget->findChild<QSpinBox*>(u"inputSpinBox2"_s); auto *outputWidget = formWidget->findChild<QLabel*>(u"outputWidget"_s);
양식에서 제공하는 출력 위젯을 수정하는 슬롯은 계산기 양식 예제와 비슷한 방식으로 정의되지만, 람다를 사용하여 찾은 위젯을 캡처한다는 점을 제외하면 다릅니다:
auto updateResult = [inputSpinBox1, inputSpinBox2, outputWidget]() { const int sum = inputSpinBox1->value() + inputSpinBox2->value(); outputWidget->setText(QString::number(sum)); }; QObject::connect(inputSpinBox1, &QSpinBox::valueChanged, formWidget, updateResult); QObject::connect(inputSpinBox2, &QSpinBox::valueChanged, formWidget, updateResult);
양식 위젯이 레이아웃에 추가되고 창 제목이 설정됩니다:
auto *layout = new QVBoxLayout(&w); layout->addWidget(formWidget); w.setWindowTitle(QCoreApplication::translate("CalculatorForm", "Calculator Builder"));
이 접근 방식의 장점은 애플리케이션이 실행될 때 양식을 교체할 수 있지만 적절한 이름이 지정되어 있는 한 포함된 위젯을 계속 조작할 수 있다는 것입니다.
그러나 런타임에 폼을 로드하면 User Interface Compiler (uic ) 도구를 사용하여 C++ 코드로 변환하는 것에 비해 런타임 비용이 발생합니다.
© 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.