ウィジェットチュートリアル - 子ウィジェット

前の例で作成したウィンドウに、そのコンストラクタに `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.