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  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Basic Layouts Example

Files:

The Basic Layouts example shows how to use the standard layout managers that are available in Qt: QBoxLayout, QGridLayout and QFormLayout.

Screenshot of the Basic Layouts example

The QBoxLayout class lines up widgets horizontally or vertically. QHBoxLayout and QVBoxLayout are convenience subclasses of QBoxLayout. QGridLayout lays out widgets in cells by dividing the available space into rows and columns. QFormLayout, on the other hand, lays out its children in a two-column form with labels in the left column and input fields in the right column.

Dialog Class Definition

 class Dialog : public QDialog
 {
     Q_OBJECT

 public:
     Dialog();

 private:
     void createMenu();
     void createHorizontalGroupBox();
     void createGridGroupBox();
     void createFormGroupBox();

     enum { NumGridRows = 3, NumButtons = 4 };

     QMenuBar *menuBar;
     QGroupBox *horizontalGroupBox;
     QGroupBox *gridGroupBox;
     QGroupBox *formGroupBox;
     QTextEdit *smallEditor;
     QTextEdit *bigEditor;
     QLabel *labels[NumGridRows];
     QLineEdit *lineEdits[NumGridRows];
     QPushButton *buttons[NumButtons];
     QDialogButtonBox *buttonBox;

     QMenu *fileMenu;
     QAction *exitAction;
 };

The Dialog class inherits QDialog. It is a custom widget that displays its child widgets using the geometry managers: QHBoxLayout, QVBoxLayout, QGridLayout and QFormLayout.

We declare four private functions to simplify the class constructor: The createMenu(), createHorizontalGroupBox(), createGridGroupBox() and createFormGroupBox() functions create several widgets that the example uses to demonstrate how the layout affects their appearances.

Dialog Class Implementation

 Dialog::Dialog()
 {
     createMenu();
     createHorizontalGroupBox();
     createGridGroupBox();
     createFormGroupBox();

In the constructor, we first use the createMenu() function to create and populate a menu bar and the createHorizontalGroupBox() function to create a group box containing four buttons with a horizontal layout. Next we use the createGridGroupBox() function to create a group box containing several line edits and a small text editor which are displayed in a grid layout. Finally, we use the createFormGroupBox() function to create a group box with three labels and three input fields: a line edit, a combo box and a spin box.

     bigEditor = new QTextEdit;
     bigEditor->setPlainText(tr("This widget takes up all the remaining space "
                                "in the top-level layout."));

     buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
                                      | QDialogButtonBox::Cancel);

     connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
     connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

We also create a big text editor and a dialog button box. The QDialogButtonBox class is a widget that presents buttons in a layout that is appropriate to the current widget style. The preferred buttons can be specified as arguments to the constructor, using the QDialogButtonBox::StandardButtons enum.

Note that we don't have to specify a parent for the widgets when we create them. The reason is that all the widgets we create here will be added to a layout, and when we add a widget to a layout, it is automatically reparented to the widget the layout is installed on.

     QVBoxLayout *mainLayout = new QVBoxLayout;

The main layout is a QVBoxLayout object. QVBoxLayout is a convenience class for a box layout with vertical orientation.

In general, the QBoxLayout class takes the space it gets (from its parent layout or from the parent widget), divides it up into a series of boxes, and makes each managed widget fill one box. If the QBoxLayout's orientation is Qt::Horizontal the boxes are placed in a row. If the orientation is Qt::Vertical, the boxes are placed in a column. The corresponding convenience classes are QHBoxLayout and QVBoxLayout, respectively.

     mainLayout->setMenuBar(menuBar);

When we call the QLayout::setMenuBar() function, the layout places the provided menu bar at the top of the parent widget, and outside the widget's content margins. All child widgets are placed below the bottom edge of the menu bar.

     mainLayout->addWidget(horizontalGroupBox);
     mainLayout->addWidget(gridGroupBox);
     mainLayout->addWidget(formGroupBox);
     mainLayout->addWidget(bigEditor);
     mainLayout->addWidget(buttonBox);

We use the QBoxLayout::addWidget() function to add the widgets to the end of layout. Each widget will get at least its minimum size and at most its maximum size. It is possible to specify a stretch factor in the addWidget() function, and any excess space is shared according to these stretch factors. If not specified, a widget's stretch factor is 0.

     setLayout(mainLayout);

     setWindowTitle(tr("Basic Layouts"));
 }

We install the main layout on the Dialog widget using the QWidget::setLayout() function, and all of the layout's widgets are automatically reparented to be children of the Dialog widget.

 void Dialog::createMenu()
 {
     menuBar = new QMenuBar;

     fileMenu = new QMenu(tr("&File"), this);
     exitAction = fileMenu->addAction(tr("E&xit"));
     menuBar->addMenu(fileMenu);

     connect(exitAction, SIGNAL(triggered()), this, SLOT(accept()));
 }

In the private createMenu() function we create a menu bar, and add a pull-down File menu containing an Exit option.

 void Dialog::createHorizontalGroupBox()
 {
     horizontalGroupBox = new QGroupBox(tr("Horizontal layout"));
     QHBoxLayout *layout = new QHBoxLayout;

     for (int i = 0; i < NumButtons; ++i) {
         buttons[i] = new QPushButton(tr("Button %1").arg(i + 1));
         layout->addWidget(buttons[i]);
     }
     horizontalGroupBox->setLayout(layout);
 }

When we create the horizontal group box, we use a QHBoxLayout as the internal layout. We create the buttons we want to put in the group box, add them to the layout and install the layout on the group box.

 void Dialog::createGridGroupBox()
 {
     gridGroupBox = new QGroupBox(tr("Grid layout"));

In the createGridGroupBox() function we use a QGridLayout which lays out widgets in a grid. It takes the space made available to it (by its parent layout or by the parent widget), divides it up into rows and columns, and puts each widget it manages into the correct cell.

     for (int i = 0; i < NumGridRows; ++i) {
         labels[i] = new QLabel(tr("Line %1:").arg(i + 1));
         lineEdits[i] = new QLineEdit;
         layout->addWidget(labels[i], i + 1, 0);
         layout->addWidget(lineEdits[i], i + 1, 1);
     }

For each row in the grid we create a label and an associated line edit, and add them to the layout. The QGridLayout::addWidget() function differ from the corresponding function in QBoxLayout: It needs the row and column specifying the grid cell to put the widget in.

     smallEditor = new QTextEdit;
     smallEditor->setPlainText(tr("This widget takes up about two thirds of the "
                                  "grid layout."));
     layout->addWidget(smallEditor, 0, 2, 4, 1);

QGridLayout::addWidget() can in addition take arguments specifying the number of rows and columns the cell will be spanning. In this example, we create a small editor which spans three rows and one column.

For both the QBoxLayout::addWidget() and QGridLayout::addWidget() functions it is also possible to add a last argument specifying the widget's alignment. By default it fills the whole cell. But we could, for example, align a widget with the right edge by specifying the alignment to be Qt::AlignRight.

     layout->setColumnStretch(1, 10);
     layout->setColumnStretch(2, 20);
     gridGroupBox->setLayout(layout);
 }

Each column in a grid layout has a stretch factor. The stretch factor is set using QGridLayout::setColumnStretch() and determines how much of the available space the column will get over and above its necessary minimum.

In this example, we set the stretch factors for columns 1 and 2. The stretch factor is relative to the other columns in this grid; columns with a higher stretch factor take more of the available space. So column 2 in our grid layout will get more of the available space than column 1, and column 0 will not grow at all since its stretch factor is 0 (the default).

Columns and rows behave identically; there is an equivalent stretch factor for rows, as well as a QGridLayout::setRowStretch() function.

 void Dialog::createFormGroupBox()
 {
     formGroupBox = new QGroupBox(tr("Form layout"));
     QFormLayout *layout = new QFormLayout;
     layout->addRow(new QLabel(tr("Line 1:")), new QLineEdit);
     layout->addRow(new QLabel(tr("Line 2, long text:")), new QComboBox);
     layout->addRow(new QLabel(tr("Line 3:")), new QSpinBox);
     formGroupBox->setLayout(layout);
 }

In the createFormGroupBox() function, we use a QFormLayout to neatly arrange objects into two columns - name and field. There are three QLabel objects for names with three corresponding input widgets as fields: a QLineEdit, a QComboBox and a QSpinBox. Unlike QBoxLayout::addWidget() and QGridLayout::addWidget(), we use QFormLayout::addRow() to add widgets to the layout.

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 103
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 56
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 97
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 32
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 231
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 103
  7. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
Page suivante

Le Qt Developer Network au hasard

Logo

Applications mobiles modernes avec Qt et QML

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 4.7-snapshot
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