简单的锚点布局示例

演示了图形视图场景中的锚点布局。

“简单锚点布局”示例展示了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 的左上角。这可以通过以下两个步骤实现:

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

或者通过一步完成:

    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);

在控件b 下方放置第三个控件c :

    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.