Exemplo simples de layout de âncora

Demonstra o layout de âncoras em uma cena de visualização gráfica.

O exemplo “Layout simples de âncora” mostra o uso básico da classe QGraphicsAnchorLayout.

Aplicativo que utiliza layouts de âncora para posicionar widgets

O exemplo começa criando um ` QGraphicsScene ` (scene), três widgets (a, b e c) e um `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;

Primeiro, ele ancora o canto superior esquerdo do item a ao canto superior esquerdo de layout. Isso pode ser feito em duas etapas:

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

Ou em uma única etapa:

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

Em seguida, a âncora direita de a é fixada à âncora esquerda de b, e a parte superior do item b é fixada à parte inferior de a.

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

Coloque um terceiro widget c abaixo do widget b:

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

Os itens b e c estão alinhados horizontalmente entre si:

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

O item c está alinhado ao ponto inferior direito de layout

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

Por fim, QGraphicsWidget w é exibido em 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();

Projeto de exemplo em @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.