пример Basic Layouts
Файлы:
The Basic Layouts example shows how to use the standard layout managers that are available in Qt: QBoxLayout, QGridLayout and QFormLayout.

Класс QBoxLayout располагает виджеты в линию, горизонтально или вертикально. QHBoxLayout и QVBoxLayout - вспомогательные потомки класса 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.
Определение класса диалога
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;
};
Класс Dialog наследует 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 createa 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()));
Мы также создали большой редактор текста и кнопку диалогового окна. Класс QDialogButtonBox является виджетом, который представляет кнопки в компоновщике, которые относятся к текущему стилю виджета. Предпочтительные кнопки можно указать в качесвте параметров в конструкторе, используя перечисление QDialogButtonBox::StandardButtons.
Помните, что мы не должны указывать родителей при создании элементов. Причина этого в том, что когда все виджеты будут добавлены в компоновщик, он автоматически станет их предком.
QVBoxLayout *mainLayout = new QVBoxLayout;
Главный компоновщик - объект QVBoxLayout. QVBoxLayout - вспомогательный класс для группового вывода с вертикальной ориентацией.
В основном, класс QBoxLayout берёт пространство оттуда, откуда он запускается (от его предка-компоновщика или родительского виджета), делит полученное место на ряд областей и заносит в каждый виджет в одну область. 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. Все дочерние виджеты помещаются под нижнем краем панели меню.
mainLayout->addWidget(horizontalGroupBox);
mainLayout->addWidget(gridGroupBox);
mainLayout->addWidget(formGroupBox);
mainLayout->addWidget(bigEditor);
mainLayout->addWidget(buttonBox);
Мы используем QBoxLayout::addWidget() функцию для добавления виджетов в конец компоновщика. Каждый виджет получит столько место, сколько ему минимально необходимо, но сколько при этом он может максимально занять. Возможно определить фактор растяжения в функции addWidget(), и любое освободившееся место будет распределено в соответствии с этим параметром. Если не определено, фактор растяжения равен 0.
setLayout(mainLayout);
setWindowTitle(tr("Basic Layouts"));
}
Мы устанавливаем главный компоновщик виджета Dialog с помощью функции QWidget::setLayout(), и все виджеты компоновщика автоматически становятся потомками виджета Dialog.
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()));
}
В закрытой функции createMenu() мы создаём строку меню и добавляем в неё выпадающее меню File, содержащее пункт Exit.
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);
}
Когда мы создаём группу горизонтально расположенных элементов, мы используем QHBoxLayout в качестве внутреннего компоновщика. Мы создаём кнопки, которые мы хотим поместить в компоновщик, добавляем их и устанавливаем компоновщик для отображения.
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);
}
Каждый столбец в таблице имеет растягивающий фактор. Растягивающий фактор устанавливается с помощью QGridLayout::setColumnStretch() и определяет, сколько доступного пространства будет предоставляться столбцам выше необходимого минимума.
В этом примере мы устанавливали факторы растяжения для стобцов 1 и 2. Фактор растяжения определяется в зависимости от других столбцов таблицы; столбцы с более высоким значением занимают больше доступного места. Потому столбец 2 в нашем случае получит больше доступного пространства, чем 1, а столбец 0 не будет увеличиваться, так как его фактор растяжения равен 0 (по умолчанию).
Столбцы и строки ведут себя одинаково; по аналогии, фактор растяжения для строк может быть установлен с помощью QGridLayout::setRowStretch().
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.
Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) |
Торговые марки |
Qt 4.5.3 |
|