Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Classes  ·  Annotées  ·  Hiérarchie  ·  Fonctions  ·  Structure  · 

Layout Classes


The Qt layout system provides a simple and powerful way of specifying the layout of child widgets.

By specifying the logical layout once, you get the following benefits:

  • Positioning of child widgets.
  • Sensible default sizes for top-level widgets.
  • Sensible minimum sizes for top-level widgets.
  • Resize handling.
  • Automatic update when contents change:
    • Font size, text or other contents of subwidgets.
    • Hiding or showing a subwidget.
    • Removal of subwidget.

Layout Widgets

The easiest way to give your widgets a good layout is to use the layout widgets: QHBox, QVBox and QGrid. A layout widget automatically lays out its children in the order they are constructed. To make more complex layouts, you can nest layout widgets inside each other.

QHBox
A QHBox lays out its children in a horizontal row, left to right.
QHBox with five children.

QVBox
A QVBox lays out its children in a vertical row, top to bottom.
QVBox with five children.
QGrid
A QGrid lays out its children in a table. You specify how many columns the table has, and it is filled left to right, beginning a new row when the previous is filled up. The grid is fixed; the children will not flow to other rows as the widget is resized.
Two-column QGrid with five children.

The grid above can be produced by the following code:

    QGrid *main = new QGrid( 2 ); // a 2 x n grid
    new QLabel( "One", main );
    new QLabel( "Two", main );
    new QLabel( "Three", main );
    new QLabel( "Four", main );
    new QLabel( "Five", main );

You can adjust the layout somewhat by calling setMinimumSize() or setFixedSize() on the children.

QLayout

If you need more control over the layout, use a QLayout subclass. The layout classes included in Qt 2.1 are QGridLayout and QBoxLayout. (QHBoxLayout and QVBoxLayout are trivial subclasses of QBoxLayout, that are simpler to use and make the code easier to read.)

When you use a layout, you have to insert each child both into its parent widget (done in the constructor) and into its layout (typically done with a function called addWidget()). This way, you can give layout parameters for each widget, specifying properties like alignment, stretch, and placement.

The following code makes a grid like the one above, with a couple of improvements:

    QWidget *main = new QWidget;

    //make a 1x1 grid, it will auto-expand:
    QGridLayout *grid = new QGridLayout( main, 1, 1 );

    //add the first four widgets with (row, column) addressing
    grid->addWidget( new QLabel( "One", main ), 0, 0 );
    grid->addWidget( new QLabel( "Two", main ), 0, 1 );
    grid->addWidget( new QLabel( "Three", main ), 1, 0 );
    grid->addWidget( new QLabel( "Four", main ), 1, 1 );

    //add the last widget on row 2, let it span from column 0 to
    //column 1, and let it be aligned center.   
    grid->addMultiCellWidget( new QLabel( "Five", main ), 2, 2, 0, 1,
                              Qt::AlignCenter );

    //let the ratio between the widths of columns 0 and 1 be 2:3.
    grid->setColStretch( 0, 2 );
    grid->setColStretch( 1, 3 );

You can insert layouts inside a layout by giving the parent layout as a parameter in the constructor.

    QWidget*       main = new QWidget;
    QLineEdit*    field = new QLineEdit( main );
    QPushButton*     ok = new QPushButton( "OK", main );
    QPushButton* cancel = new QPushButton( "Cancel", main );
    QLabel*       label = new QLabel( "Where do you want to go?", main );

    QVBoxLayout *vbox    = new QVBoxLayout( main ); // A layout on a widget
    vbox->addWidget( label );
    vbox->addWidget( field );

    QHBoxLayout *buttons = new QHBoxLayout( vbox ); // A layout inside a layout
    buttons->addWidget( ok );
    buttons->addWidget( cancel );

If you are not satisfied with the default placement, you can create the layout without a parent and then insert it with addLayout().

Custom Layouts

If the built-in layout classes are not sufficient, you can define your own. You will have to make a subclass of QLayout that handles resizing and size calculations, as well as a subclass of QGLayoutIterator to iterate over your layout class.

See the Custom Layout page for an in-depth description.

Custom Widgets In Layouts

When you make your own widget class, you should also communicate its layout properties. If the widget has a QLayout, this is already taken care of. If the widget does not have any children, or uses manual layout, you should reimplement the following QWidget member functions:

sizeHint()
Returns the preferred size of the widget.
minimumSizeHint()
Returns the smallest size the widget can have.
sizePolicy()
Returns a QSizePolicy; a value describing the space requirements of the widget.

Call updateGeometry() whenever the size hint, minimum size hint or size policy changes. This will cause a layout recalculation. Multiple calls to updateGeometry() will only cause one recalculation.

If the preferred height of your widget depends on its actual width (eg. a label with automatic word-breaking), set the hasHeightForWidth() flag in sizePolicy(), and reimplement heightForWidth().

Even if you implement heightForWidth(), it is still necessary to provide a good sizeHint(). The sizeHint() provides the preferred width of the widget, and it is used by QLayout subclasses that do not support heightForWidth() (both QGridLayout and QBoxLayout support it).

For further guidance when implementing these functions, see their implementations in existing Qt classes that have similar layout requirements to your new widget.

Manual Layout

If you are making a one-of-a-kind special layout, you can also make a custom widget as described above. Reimplement resizeEvent() to calculate the required distribution of sizes and call setGeometry() on each child.

The widget will get an event with type LayoutHint when the layout needs to be recalculated. Reimplement event() to be notified of LayoutHint events.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 79
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 6
Page suivante

Le Qt Developer Network au hasard

Logo

Les bases

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 2.3
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web