Qt随笔 - QVBoxLayout和QHBoxLayout
2017-04-03 本文已影响1451人
静_谷

- 垂直布局:QVBoxLayout
先来一两代码:
QWidget *widget = new QWidget();
QVBoxLayout * vBoxLayout = new QVBoxLayout();
QLabel *label = new QLabel("hello");
QPushButton *pushButton = new QPushButton("hi");
vBoxLayout->addWidget(label);
vBoxLayout->addWidget(pushButton);
widget->setLayout(vBoxLayout);
widget->show();
效果:

- 水平布局:QHBoxLayout
一样:
QWidget *widget = new QWidget();
QHBoxLayout * hBoxLayout = new QHBoxLayout();
QLabel *label = new QLabel("hello");
QPushButton *pushButton = new QPushButton("hi");
hBoxLayout->addWidget(label);
hBoxLayout->addWidget(pushButton);
widget->setLayout(hBoxLayout);
widget->show();

- QHBoxLayout嵌套QVBoxLayout
QWidget *widget = new QWidget();
QHBoxLayout * hBoxLayout = new QHBoxLayout();
QVBoxLayout * vBoxLayout = new QVBoxLayout();
QLabel *label_text = new QLabel("Chengdu 1 – 3 Day Weather Forecast Summary");
QLabel *label_picture = new QLabel();
label_picture->setPixmap(QPixmap(":/weather").scaled(32,32, Qt::KeepAspectRatioByExpanding));
QPushButton *pushButton = new QPushButton("more");
vBoxLayout->addWidget(label_text);
vBoxLayout->addWidget(pushButton);
hBoxLayout->addWidget(label_picture);
hBoxLayout->addLayout(vBoxLayout);
widget->setLayout(hBoxLayout);
widget->show();

- 总结
1.向布局添加一个Widget:
void QBoxLayout::addWidget(QWidget *widget, int stretch = 0, Qt::Alignment alignment = Qt::Alignment())
2.向布局再添加一个布局
void QBoxLayout::addLayout(QLayout *layout, int stretch = 0)�
3.最后,使用它来确定Widget的布局
void QWidget::setLayout(QLayout *layout)