网格布局示例
网格布局是一个强大的布局,你可以使用它进行一次水平和垂直布局。
例:
#include "mainwindow.h"
#include <QApplication>
#include <QMainWindow>
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
#include <QGroupBox>
#include <QTextEdit>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow window;
QWidget *widget = new QWidget(&window);
QGridLayout *layout = new QGridLayout(widget);
window.setCentralWidget(widget);
widget->setLayout(layout);
QGroupBox *box = new QGroupBox("Information:", widget);
layout->addWidget(box, 0, 0);
QVBoxLayout *boxLayout = new QVBoxLayout(box);
QWidget* nameWidget = new QWidget(box);
QWidget* ageWidget = new QWidget(box);
QWidget* addressWidget = new QWidget(box);
boxLayout->addWidget(nameWidget);
boxLayout->addWidget(ageWidget);
boxLayout->addWidget(addressWidget);
QHBoxLayout *nameLayout = new QHBoxLayout(nameWidget);
nameLayout->addWidget(new QLabel("Name:"));
nameLayout->addWidget(new QLineEdit(nameWidget));
QHBoxLayout *ageLayout = new QHBoxLayout(ageWidget);
ageLayout->addWidget(new QLabel("Age:"));
ageLayout->addWidget(new QLineEdit(ageWidget));
QHBoxLayout *addressLayout = new QHBoxLayout(addressWidget);
addressLayout->addWidget(new QLabel("Address:"));
addressLayout->addWidget(new QLineEdit(addressWidget));
layout->addWidget(new QPushButton("Validate", widget), 1, 0);
layout->addWidget(new QPushButton("Reset", widget), 1, 1);
layout->addWidget(new QPushButton("Cancel", widget), 1, 2);
window.show();
return a.exec();
}
给:
所以你可以看到组框只在第一列和第一行,因为 addWidget 是 layout->addWidget(box, 0, 0);
但是,如果将其更改为 layout->addWidget(box, 0, 0, 1, 3);
,则新的 0 和 3 表示你想要的小部件的行数和列数,因此它给出:
与在子窗口小部件中创建水平布局和垂直布局完全相同。