背景:
- 在现有的ui的顶端放置自定义的状态栏。Qt中的布局,可以使用QDesigner直接拖放,同样可以手写(稍显麻烦),但是常用在小部件的叠加布局上。
- 常见类是QBoxLayout及其子类QHBoxLayout和QVBoxLayout。
- 其中H代表horizon,意思是水平,即表示QHBoxLayout是水平布局。
- 其中V代表vertical,意思是垂直,即表示QVBoxLayout是垂直布局。
接口函数:
- setMargin(int):设置部件的四周边框,设置后是等长等宽的。
- setContentsMargins(int left, int top, int right, int bottom):四周的边框分别设置为不同的值。
- setContentsMargins(const QMargins &margins):设置外框边距。
- setSpacing(int):设置部件之间的间距值,比如两个label,是紧挨排放还是以一定间距排放。
- addStretch():增加一个伸缩控件,就是QDesigner中的小弹簧,弹簧位置根据此代码放置位置而定。
- addWidget(QWidget *, int stretch = 0, Qt::Alignment alignment = 0):添加一个控件。即将想显示的Label或button放入其中。
- setQirection(Direction):设置布局方向,参数为从左到右QBoxLayout::LeftToRight,从上至下QBoxLayout::TopToBottom等。
- setStretchFactor(Qwiget *w, int stretch):设置控件的拉伸系数,拉伸系数作用是当窗口大小变化时,控件会根据拉伸系数决定控件的大小。
- setStretchFactor(QLayout *l, int stretch):设置布局的拉伸系数,作用同上。
例子:
QVBoxLayout * pLayout = new QVBoxLayout();
QPushButton * p1 = new QPushButton("p1");
QPushButton * p2 = new QPushButton("p2");
QLabel * l1 = new QLabel("l1");
QLabel * l2 = new QLabel("l2");
pLayout->addStretch();//增加小弹簧
pLayout->addWidget(p1);//将之前定义的控件加入布局中
pLayout->addWidget(p2);
pLayout->addWidget(l1);
pLayout->addWidget(l2);
pLayout->setSpacing(77);//控件之间增加固定为77的间隔
pLayout->addWidget(p1,0,Qt::AlignLeft | Qt::AlignTop);//水平左,垂直上
pLayout->addWidget(p2,0,Qt::AlignRight | Qt::AlignBottom);//水平右,垂直下
pLayout->addWidget(l1,0,Qt::AlignCenter );//居中
pLayout->addWidget(l2);//不处理
pLayout->setDirection(QBoxLayout::TopToBottom);//从上到下
pLayout->setDirection(QBoxLayout::LeftToRight);//从左到右
this->setLayout(pLayout);