部件教程--使用布局

通常,子窗口部件是通过布局对象在窗口内排列的,而不是通过明确指定位置和大小。在这里,我们构建了一个标签和行编辑部件,希望将它们并排排列。

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