内容来自:http://bbs.csdn.net/topics/391053349
第一种方式是选中整个对话框,然后应用水平layout,
得到的代码如下:
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
|
class
Ui_Dialog
{
public
:
QHBoxLayout *horizontalLayout;
QPushButton *pushButton1;
QPushButton *pushButton2;
void
setupUi(QDialog *Dialog)
{
if
(Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral(
"Dialog"
));
Dialog->resize(286, 191);
horizontalLayout = new QHBoxLayout(Dialog);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QStringLiteral(
"horizontalLayout"
));
pushButton1 = new QPushButton(Dialog);
pushButton1->setObjectName(QStringLiteral(
"pushButton1"
));
horizontalLayout->addWidget(pushButton1);
pushButton2 = new QPushButton(Dialog);
pushButton2->setObjectName(QStringLiteral(
"pushButton2"
));
horizontalLayout->addWidget(pushButton2);
retranslateUi(Dialog);
QMetaObject::connectSlotsByName(Dialog);
}
// setupUi
|
第二种方式中选中对话框上的对象,然后应用布局,
代码如下:
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
|
class
Ui_Dialog
{
public
:
QWidget *widget;
QHBoxLayout *horizontalLayout;
QPushButton *pushButton1;
QPushButton *pushButton2;
void
setupUi(QDialog *Dialog)
{
if
(Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral(
"Dialog"
));
Dialog->resize(286, 191);
widget = new QWidget(Dialog);
widget->setObjectName(QStringLiteral(
"widget"
));
widget->setGeometry(QRect(40, 80, 158, 25));
horizontalLayout =
new
QHBoxLayout(widget);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QStringLiteral(
"horizontalLayout"
));
horizontalLayout->setContentsMargins(0, 0, 0, 0);
pushButton1 = new QPushButton(widget);
pushButton1->setObjectName(QStringLiteral(
"pushButton1"
));
horizontalLayout->addWidget(pushButton1);
pushButton2 = new QPushButton(widget);
pushButton2->setObjectName(QStringLiteral(
"pushButton2"
));
horizontalLayout->addWidget(pushButton2);
retranslateUi(Dialog);
QMetaObject::connectSlotsByName(Dialog);
}
// setupUi
|
从运行的结果来看,第一种方式,调整对话框大小的时候,按钮会跟着调整。但是对于原理,还是不太清楚。
而且我感觉,应该调用widget->setLayout(horizontalLayout); 而生成的代码中没有调用。这是为什么呢?
horizontalLayout = new QHBoxLayout(Dialog); //QLayout构造函数中调用了parent->setLayout(this);
就等同于:
horizontalLayout = new QHBoxLayout();
Dialog->seLayout(horizontalLayout );
因此第一种是两个按钮直接布局在Dialog中,所以会随窗体大小变化。
而第二种布局会自动创建子窗口widget,而widget在Dialog没有布局,大小不受Dialog约束,属于float状态。
看了下源代码,果然!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/*!
Constructs a new top-level QLayout, with parent \a parent.
\a parent may not be 0.
There can be only one top-level layout for a widget. It is
returned by QWidget::layout().
*/
QLayout::QLayout(QWidget *parent)
: QObject(*
new
QLayoutPrivate, parent)
{
if
(!parent)
return
;
parent->setLayout(
this
);
}
|