위젯 튜토리얼 - 레이아웃 사용하기

일반적으로 하위 위젯은 위치와 크기를 명시적으로 지정하지 않고 레이아웃 개체를 사용하여 창 안에 배열합니다. 여기서는 레이블과 줄 편집 위젯을 나란히 배치할 위젯을 만들겠습니다.

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWidget window;
    QLabel *label = new QLabel(QApplication::translate("windowlayout", "Name:"));
    QLineEdit *lineEdit = new QLineEdit();

    QHBoxLayout *layout = new QHBoxLayout();
    layout->addWidget(label);
    layout->addWidget(lineEdit);
    window.setLayout(layout);
    window.setWindowTitle(
        QApplication::translate("windowlayout", "Window layout"));
    window.show();
    return app.exec();
}

우리가 구성한 layout 객체는 addWidget() 함수를 사용하여 제공된 위젯의 위치와 크기를 관리합니다. 레이아웃 자체는 setLayout() 호출을 통해 창 자체에 제공됩니다. 레이아웃은 해당 레이아웃이 관리하는 위젯(및 다른 레이아웃)에 미치는 영향을 통해서만 볼 수 있습니다.

위 예시에서는 각 위젯의 소유권이 즉시 명확하지 않습니다. 위젯과 레이아웃을 부모 객체 없이 구성했기 때문에 빈 창과 레이블과 줄 편집이 포함된 두 개의 개별 창이 표시될 것으로 예상할 수 있습니다. 그러나 레이아웃에 레이블과 줄 편집을 관리하도록 지시하고 창에 레이아웃을 설정하면 위젯과 레이아웃 자체가 모두 창의 자식이 되도록 ''부모가 변경''됩니다.

예제 프로젝트 @ 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.