이 페이지에서

계산기 양식

Qt Widgets Designer 로 생성된 양식을 애플리케이션에서 사용하는 방법.

'계산기 양식 예제'는 ` QWidget `의 하위 클래스에서 제공하는 사용자 인터페이스 정보를 활용하여, ` Qt Widgets Designer `로 생성된 양식을 애플리케이션에서 사용하는 방법을 보여줍니다.

‘계산기 양식’ 예제의 스크린샷

이 예제에는 정수 값을 입력하는 데 사용되는 두 개의 스핀 박스와 그 합계를 표시하는 레이블이 있습니다. 두 스핀 박스 중 하나가 업데이트될 때마다, 위젯과 양식 간의 신호-슬롯 연결을 통해 레이블도 함께 업데이트됩니다.

준비

이 예제의 사용자 인터페이스는 전적으로 Qt Widgets Designer 를 사용하여 설계되었습니다. 그 결과, 폼과 사용된 위젯, 이들 간의 신호-슬롯 연결, 그리고 기타 표준 사용자 인터페이스 속성을 설명하는 UI 파일이 생성됩니다.

이 예제가 이 파일을 사용할 수 있도록 하려면, CMAKE_AUTOUIC 기능을 활성화하고 소스 파일에 UI 파일을 명시해야 합니다:

set(CMAKE_AUTOUIC ON)

qt_add_executable(calculatorform
    calculatorform.cpp calculatorform.h calculatorform.ui
    main.cpp
)

qmake 을 사용하려면 예제의 프로젝트 파일에 ` FORMS ` 선언을 포함해야 합니다:

FORMS       = calculatorform.ui

프로젝트를 빌드하면 uic 가 폼을 생성할 수 있도록 해주는 헤더 파일을 생성합니다.

CalculatorForm 클래스 정의

CalculatorForm 클래스는 calculatorform.ui 파일에 설명된 사용자 인터페이스를 사용합니다. 폼과 그 내용에 접근하려면 빌드 과정에서 uic 에 의해 생성된 ui_calculatorform.h 헤더 파일을 포함해야 합니다:

#include "ui_calculatorform.h"

폼 자체가 QWidget 를 기반으로 하므로, QWidget 를 상속받아 CalculatorForm 클래스를 정의합니다:

class CalculatorForm : public QWidget
{
    Q_OBJECT

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

private slots:
    void updateResult();

private:
    Ui::CalculatorForm ui;
};

생성자 외에도, 이 클래스에는 계산을 수행하고 그에 따라 출력 위젯을 업데이트하는 비공개 슬롯 ` updateResult() `이 포함되어 있습니다. 비공개 멤버 변수 ` ui `은 폼을 참조하며, 사용자 인터페이스의 내용에 접근하는 데 사용됩니다.

CalculatorForm 클래스 구현

생성자는 단순히 기본 클래스의 생성자를 호출하고, 폼의 사용자 인터페이스를 설정하며, QSpinBox::valueChanged() 신호를 updateResult() 슬롯에 연결합니다.

CalculatorForm::CalculatorForm(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    connect(ui.inputSpinBox1, &QSpinBox::valueChanged, this, &CalculatorForm::updateResult);
    connect(ui.inputSpinBox2, &QSpinBox::valueChanged, this, &CalculatorForm::updateResult);
}

사용자 인터페이스는 setupUI() 함수를 통해 설정됩니다. 이 함수에 this 을 인수로 전달하여 CalculatorForm 위젯 자체를 사용자 인터페이스의 컨테이너로 사용합니다.

updateResult() 슬롯은 값들을 더하고 그 결과를 출력 위젯에 설정합니다:

void CalculatorForm::updateResult()
{
    const int sum = ui.inputSpinBox1->value() + ui.inputSpinBox2->value();
    ui.outputWidget->setText(QString::number(sum));
}

스핀 박스 중 하나의 값이 변경될 때마다 호출됩니다.

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

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