布局的概念
在实际的编程中,一个图形窗口可能会有多个控件。比如说一个图形窗口中会有一些按钮,一些文本输入框。
而这多个控件的直接的相对位置摆放的方式就称为布局。
常用布局及使用
QLayout是QT所有布局类的基类。所有布局类都适用以下函数:
void QWidget::setLayout(QLayout* l);//设置控件中的布局
void QLayout::addWidget(QWidget* w);//将控件添加进布局
QHBoxLayout 放入该布局的控件会水平排列
QVBoxLayout 放入该布局的控件会垂直排列
例子
#include <QApplication>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
#include <QHBoxLayout>
#include <QWidget>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget window;//空白的窗口空间
QHBoxLayout* layout = new QHBoxLayout(&window);//水平布局
QPushButton* btn = new QPushButton("btn", &window);//window里按钮
QLineEdit* le = new QLineEdit(&window);//window里的文本输入
QLabel* lb = new QLabel("hello",&window);//window里的标签
layout->addWidget(btn);//将控件添加进布局
layout->addWidget(le);
layout->addWidget(lb);
window.setLayout(layout);//将窗口的布局设为layout
window.show();//将窗口设为可见
return app.exec();
}
自定义窗口类
为了让代码便于管理,我们会需要将整个窗口及窗口内的控件设计成一个窗口类。在这个类的构造函数中完成整个窗口的布局。这个类的父亲可以有以下几种情况:
QWidget 普通窗口(有最大化选项)
QDialog 对话框(无最大化选项)
QMainWindow 有工具栏的窗口
例子
//MyWindow.h
#ifndef MYWINDOW_H_
#define MYWINDOW_H_
#include <QWidget>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
class MyWindow : public QWidget{//普通窗口(有做大化选项)
private:
QHBoxLayout* layout;
QPushButton* btn;
QLineEdit* le;
QLabel* lb;
public:
MyWindow(QWidget* parent = 0);//构造函数
};
#endif
//MyWindow.cpp
#include "MyWindow.h"
MyWindow::MyWindow(QWidget* parent)
:QWidget(parent)
{
layout = new QHBoxLayout(this);//放入该布局的控件会水平排列
btn = new QPushButton("btn", this);
le = new QLineEdit(this);
lb = new QLabel("hello", this);
layout->addWidget(btn);//将控件添加进布局
layout->addWidget(le);
layout->addWidget(lb);
this->setLayout(layout);设置控件中的布局为layout
}
//main.cpp
#include "MyWindow.h"
#include <QApplication>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyWindow w;
w.show();
return app.exec();
}