Qt窗口分割使用QSplitter,QSplitter继承自QFrame,QFrame又继承自QWidget。
QSplitter拆分窗口:
- 不同QSplitter对象通过指定父子关系来完成嵌套(和布局QLayout一样)
- QSplitter可以放置到指定的任何窗口内
1、代码一:把一个窗口分为左右两列
代码1
#include "dialog.h"
#include <QTextEdit>
#include <QSplitter>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
//Qt::Horizontal:水平分割窗口
//Qt::Vertical:垂直分割窗口
QSplitter *Splitter = new QSplitter(Qt::Horizontal,this);
//QSplitter *Splitter = new QSplitter(Qt::Vertical,this);
//指定QTextEdit显示在QSplitter后,后面的添加QTextEdit部件到QSplitter分割窗口的代码可以注释掉
QTextEdit *LEdt = new QTextEdit(tr("左窗口"),Splitter);
QTextEdit *REdt = new QTextEdit(tr("右窗口"),Splitter);
//Splitter->addWidget(LEdt);
//Splitter->addWidget(REdt);
//设置分割窗口的宽度比例为1:2
Splitter->setStretchFactor(0,1);
Splitter->setStretchFactor(1,2);
Splitter->show();
}
Dialog::~Dialog()
{
}
2、把一个窗口拆分为左右两列,右列再拆分为上下两列
代码2
#include "dialog.h"
#include <QTextEdit>
#include <QSplitter>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
//Qt::Horizontal:水平分割窗口
//Qt::Vertical:垂直分割窗口
//窗口分割,存在先后顺序,左窗口完成后,再右窗口
QSplitter *Lsplitter = new QSplitter(Qt::Horizontal,this);
//QSplitter *Rsplitter = new QSplitter(Qt::Vertical,Lsplitter);右窗口定义在此处,编译结果与期望结果相反
QTextEdit *LEdt = new QTextEdit(tr("左窗口"),Lsplitter);
QSplitter *Rsplitter = new QSplitter(Qt::Vertical,Lsplitter);
QTextEdit *RtopEdt = new QTextEdit(tr("右上窗口"),Rsplitter);
QTextEdit *RbtmEdt = new QTextEdit(tr("右下窗口"),Rsplitter);
//设置右窗口的上下窗口比例1:4
Rsplitter->setStretchFactor(0,1);
Rsplitter->setStretchFactor(1,4);
//设置分割窗口左右的宽度比例为1:2
Lsplitter->setStretchFactor(0,1);
Lsplitter->setStretchFactor(1,2);
Lsplitter->show();
}
Dialog::~Dialog()
{
}
3、把一个窗口分为左右两列,左窗口再拆分为上下两列
代码3
#include "dialog.h"
#include <QTextEdit>
#include <QSplitter>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
//Qt::Horizontal:水平分割窗口
//Qt::Vertical:垂直分割窗口
//左窗口分割
QSplitter *Lsplitter = new QSplitter(Qt::Vertical);
QTextEdit *LtopEdt = new QTextEdit(tr("左上窗口"),Lsplitter);
QTextEdit *LbtmEdt = new QTextEdit(tr("左下窗口"),Lsplitter);
//左窗口上下比例为1:2
Lsplitter->setStretchFactor(0,1);
Lsplitter->setStretchFactor(1,2);
//右窗口
QSplitter *Rsplitter = new QSplitter();
QTextEdit *REdt = new QTextEdit(tr("右窗口"),Rsplitter);
//整合左右窗口为一个窗口
QSplitter *MainSplitter = new QSplitter(Qt::Horizontal,this);
MainSplitter->addWidget(Lsplitter);
MainSplitter->addWidget(Rsplitter);
//设置分割窗口左右的宽度比例为4:1
MainSplitter->setStretchFactor(0,4);
MainSplitter->setStretchFactor(1,1);
MainSplitter->show();
}
Dialog::~Dialog()
{
}