Esempio di layout con ancore semplice
Mostra il layout con ancore in una scena di vista grafica.
L'esempio "Layout semplice con ancore" illustra l'utilizzo di base della classe QGraphicsAnchorLayout.

L'esempio inizia con la creazione di un oggetto ` QGraphicsScene ` (scene), di 3 widget (a, b e c) e di un `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;Per prima cosa, si ancora l’angolo superiore sinistro dell’elemento a all’angolo superiore sinistro di layout. Ciò può essere fatto in due passaggi:
layout->addAnchor(a, Qt::AnchorTop, layout, Qt::AnchorTop);
layout->addAnchor(a, Qt::AnchorLeft, layout, Qt::AnchorLeft);Oppure in un unico passaggio:
Quindi l'ancora destra di a viene ancorata all'ancora sinistra di b, e la parte superiore dell'elemento b viene ancorata alla parte inferiore di a.
layout->addAnchor(b, Qt::AnchorLeft, a, Qt::AnchorRight);
layout->addAnchor(b, Qt::AnchorTop, a, Qt::AnchorBottom);Inserisci un terzo widget c sotto il widget b:
Gli elementi b e c sono ancorati l’uno all’altro in orizzontale:
layout->addAnchors(b, c, Qt::Horizontal);L’elemento c è ancorato al punto in basso a destra di layout
Infine, QGraphicsWidget w viene visualizzato in 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();© 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.