シンプルなアンカーレイアウトの例

グラフィックスビューのシーン上で、アンカーレイアウトの動作を実演します。

「シンプルなアンカーレイアウト」の例では、QGraphicsAnchorLayout クラスの基本的な使用方法を示しています。

アンカーレイアウトを使用してウィジェットを配置するアプリケーション

このサンプルでは、まずQGraphicsScene (scene )、3つのウィジェット(a 、b 、c )、およびQGraphicsAnchorLayout(layout )を作成します。

    QGraphicsScene scene;

    Widget *a = new Widget(Qt::blue, Qt::white, "a");
    a->setPreferredSize(100, 100);
    Widget *b = new Widget(Qt::green, Qt::black, "b");
    b->setPreferredSize(100, 100);
    Widget *c = new Widget(Qt::red, Qt::black, "c");
    c->setPreferredSize(100, 100);

    QGraphicsAnchorLayout *layout = new QGraphicsAnchorLayout;

まず、アイテムa の左上隅をlayout の左上隅にアンカーします。これは2つの手順で実行できます:

    layout->addAnchor(a, Qt::AnchorTop, layout, Qt::AnchorTop);
    layout->addAnchor(a, Qt::AnchorLeft, layout, Qt::AnchorLeft);

あるいは、1つのステップで行うこともできます:

    layout->addCornerAnchors(a, Qt::TopLeftCorner, layout, Qt::TopLeftCorner);

次に、a の右アンカーをb の左アンカーに固定し、b のトップをa のボトムに固定します。

    layout->addAnchor(b, Qt::AnchorLeft, a, Qt::AnchorRight);
    layout->addAnchor(b, Qt::AnchorTop, a, Qt::AnchorBottom);

3つ目のウィジェットc を、ウィジェットb の下に配置します:

    layout->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);

アイテムb とc は、水平方向に互いに固定されています:

    layout->addAnchors(b, c, Qt::Horizontal);

項目 c は、layout

    layout->addCornerAnchors(c, Qt::BottomRightCorner, layout, Qt::BottomRightCorner);

最終的に、QGraphicsWidget とw は、QGraphicsView view に表示されます。

    auto w = new QGraphicsWidget(nullptr, Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    w->setPos(20, 20);
    w->setMinimumSize(100, 100);
    w->setPreferredSize(320, 240);
    w->setLayout(layout);
    w->setWindowTitle(QApplication::translate("simpleanchorlayout", "QGraphicsAnchorLayout in use"));
    scene.addItem(w);

    QGraphicsView view;
    view.setScene(&scene);
    view.setWindowTitle(QApplication::translate("simpleanchorlayout", "Simple Anchor Layout"));

    view.resize(360, 320);
    view.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.