QT布局QGridLayout QHBoxLayout QVBoxLayout简要分析

在分析之前,先吐槽下M$的MFC,竟然没有相对布局!(至少我不知道,每次都是代码中控制布局),
M$这么多年,也不发展一下,你看C#都有相对布局...

参考精通Qt4编程(第2版),先看看总体的布局图

然后看看代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
CLoginDlg::CLoginDlg(QWidget* parent/* = NULL */) : QDialog(parent)
{
    //QGridLayout
    usrLabel = new QLabel(tr("用户名:"));
    pwdLabel = new QLabel(tr("密  码:"));
    usrLineEdit = new QLineEdit;
    pwdLineEdit = new QLineEdit;
    pwdLineEdit->setEchoMode(QLineEdit::Password);
    gridLayout = new QGridLayout;
    gridLayout->addWidget(usrLabel, 0, 0, 1, 1);
    gridLayout->addWidget(usrLineEdit, 0, 1, 1, 3);
    gridLayout->addWidget(pwdLabel, 1, 0, 1, 1);
    gridLayout->addWidget(pwdLineEdit, 1, 1, 1, 3);

    //QHBoxLayout
    okBtn = new QPushButton(tr("确定"));
    cancelBtn = new QPushButton(tr("取消"));
    btnLayout = new QHBoxLayout;
    btnLayout->setSpacing(60);
    btnLayout->addWidget(okBtn);
    btnLayout->addWidget(cancelBtn);

    //QVBoxLayout
    dlgLayout = new QVBoxLayout;
    dlgLayout->setMargin(40);
    dlgLayout->addLayout(gridLayout);
    dlgLayout->addStretch(40);
    dlgLayout->addLayout(btnLayout);
    setLayout(dlgLayout);

    connect(okBtn, SIGNAL(clicked()), this, SLOT(accept()));
    connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));

    setWindowTitle(tr("登录"));
    resize(300, 200);
}

这里面一共有3个布局QGridLayout/QHBoxLayout/QVBoxLayout
看看QGridLayout

局管理器gridLayout中的具体位置,其中前两个实参分别表示行和列的位置(行号和列号),后两个参数分别表示行的跨度和列的跨度
gridLayout->addWidget(usrLineEdit, 0, 1, 1, 3);
QHBoxLayout/QVBoxLayout比较简单,一个是水平的排,一个是垂直的排

运行代码,结果如下:

为了方便看,我做了标识,然后放大窗口,又做了标识


图中的40,就是这行代码的功劳:dlgLayout->setMargin(40);
60是这行代码的功劳:btnLayout->setSpacing(60);
还有一行代码dlgLayout->addStretch(40),作如下解释:

函数QVBoxLayout::addStretch()函数在垂直布局管理器dlgLayout对象中加入一个大小为40的stretch,这将使得布局管理器gridLayout和btnLayout之间的默认距离设置为40,同时当上下拉伸对话框的高度时,该stretch可以自由伸缩,从而保证gridLayout和btnLayout管理器内部各窗口部件的高度以及彼此间的垂直距离保持不变。

以上,由于代码比较简单,大家也能一目了然吧.
可以看出,字体大小并不会随着窗口的变大而变大(当然控件的高度也没有变).

文章备份地址:https://netpt.net/forum.php?mod=viewthread&tid=37

承接Windows/Linux桌面应用开发(C/C++),专业coding10年+,值得信赖.
VC/MFC/QT
QQ:13571089