目前的GUI开发方式:绝对定位
直接在像素级指定各个组件的位置和大小
void QWidget::move(int x, int y)
void QWidget::resize(int x, int y)
问题:




#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
class Widget : public QWidget
{
Q_OBJECT
private:
QPushButton TestBtn1;
QPushButton TestBtn2;
QPushButton TestBtn3;
QPushButton TestBtn4;
void initBtn();
void initControl();
void testVBoxLayout();
void testHBoxLayout();
void testVHBoxLayout();
public:
Widget(QWidget *parent = 0);
~Widget();
};
#endif // WIDGET_H
#include "Widget.h"
#include <QBoxLayout>
Widget::Widget(QWidget *parent) : QWidget(parent),
TestBtn1(this), TestBtn2(this), TestBtn3(this), TestBtn4(this)
{
initBtn(); // 初始化按钮控件
//initControl(); // 绝对定位,无法自适应窗口变化
//testVBoxLayout(); // 垂直布局管理
//testHBoxLayout(); // 水平布局管理
testVHBoxLayout(); // 嵌套布局管理
}
Widget::~Widget()
{
}
void Widget::initBtn()
{
TestBtn1.setText("Test Button 1");
TestBtn2.setText("Test Button 2");
TestBtn3.setText("Test Button 3");
TestBtn4.setText("Test Button 4");
// 设置按钮最小大小
TestBtn1.setMinimumSize(160, 30);
TestBtn2.setMinimumSize(160, 30);
TestBtn3.setMinimumSize(160, 30);
TestBtn4.setMinimumSize(160, 30);
// 设置按钮大小策略
TestBtn1.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
TestBtn2.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
TestBtn3.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
TestBtn4.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
void Widget::initControl()
{
TestBtn1.setText("Test Button 1");
TestBtn1.move(20, 20);
TestBtn1.resize(160, 30);
TestBtn2.setText("Test Button 2");
TestBtn2.move(20, 70);
TestBtn2.resize(160, 30);
TestBtn3.setText("Test Button 3");
TestBtn3.move(20, 120);
TestBtn3.resize(160, 30);
TestBtn4.setText("Test Button 4");
TestBtn4.move(20, 170);
TestBtn4.resize(160, 30);
}
void Widget::testVBoxLayout()
{
QVBoxLayout* layout = new QVBoxLayout();
// 布局管理器添加窗口控件
layout->addWidget(&TestBtn1);
layout->addWidget(&TestBtn2);
layout->addWidget(&TestBtn3);
layout->addWidget(&TestBtn4);
// 布局管理器设置控件间的间距
layout->setSpacing(20);
// 设置当前窗口的布局管理器
setLayout(layout);
}
void Widget::testHBoxLayout()
{
QHBoxLayout* layout = new QHBoxLayout();
// 布局管理器添加窗口控件
layout->addWidget(&TestBtn1);
layout->addWidget(&TestBtn2);
layout->addWidget(&TestBtn3);
layout->addWidget(&TestBtn4);
// 布局管理器设置控件间的间距
layout->setSpacing(20);
// 设置当前窗口的布局管理器
setLayout(layout);
}
void Widget::testVHBoxLayout()
{
QHBoxLayout* hLayout1 = new QHBoxLayout();
QHBoxLayout* hLayout2 = new QHBoxLayout();
QVBoxLayout* vLayout = new QVBoxLayout();
hLayout1->addWidget(&TestBtn1);
hLayout1->addWidget(&TestBtn2);
hLayout1->setSpacing(20);
hLayout2->addWidget(&TestBtn3);
hLayout2->addWidget(&TestBtn4);
hLayout2->setSpacing(20);
vLayout->addLayout(hLayout1);
vLayout->addLayout(hLayout2);
vLayout->setSpacing(20);
setLayout(vLayout);
}
#include "Widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}