小部件教程 - 子小部件

我们可以通过在构造函数中将 `window ` 作为父窗口参数传递,向上一示例中创建的窗口添加子控件。在此示例中,我们将一个按钮添加到窗口中,并将其放置在特定位置:

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWidget window;
    window.resize(320, 240);
    window.setWindowTitle
          (QApplication::translate("childwidget", "Child widget"));
    window.show();

    QPushButton *button = new QPushButton(
        QApplication::translate("childwidget", "Press me"), &window);
    button->move(100, 100);
    button->show();
    return app.exec();
}
将按钮作为子控件的窗口

该按钮现在是窗口的子控件,当窗口被销毁时,它也将被删除。请注意,隐藏或关闭窗口并不会自动销毁该窗口。只有当示例退出时,窗口才会被销毁。

示例项目 @ 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.