Qt拆分窗口可以使用QSplitter,也可以使用比较容易使用布局控件来完成,如果有需要对界面进行切割,可以使用QSplitter进行简易的控件拼接。
注意:QSplitter 继承自QFrame,而QFrame又继承自QWidget,这点很重要。
注意添加头文件
#include <QSplitter>
#include <QTextEdit>
对于使用QSplitter拆分窗口:
demo1
QSplitter *pSpliter = new QSplitter(Qt::Horizontal);
//此注释指定父窗口,打开后,后面的pSpliter->addWidget(pLeftEdt); 可以注释掉
//QTextEdit* pLeftEdt = new QTextEdit(pSpliter);
QTextEdit* pLeftEdt = new QTextEdit;
pLeftEdt->setText(QObject::tr("LeftWindow"));
//此注释指定父窗口,打开后,后面的pSpliter->addWidget(pRightEdt); 可以注释掉
//QTextEdit* pRightEdt = new QTextEdit(pSpliter);
QTextEdit* pRightEdt = new QTextEdit;
pRightEdt->setText(QObject::tr("RightWindow"));
pSpliter->addWidget(pLeftEdt);
pSpliter->addWidget(pRightEdt);
pSpliter->setStretchFactor(0, 1);//下面两句设置左右两列的宽度比为1:4
pSpliter->setStretchFactor(1, 4);
demo2
QSplitter *pSpliter = new QSplitter(Qt::Horizontal);
QTextEdit* pLeftEdt = new QTextEdit(pSpliter);
pLeftEdt->setText(QObject::tr("LeftWindow"));
QSplitter *pRightSpliter = new QSplitter(Qt::Vertical, pSpliter);
QTextEdit* pRightTopEdt = new QTextEdit(pRightSpliter);
pRightTopEdt->setText(QObject::tr("Right Top Window"));
QTextEdit* pRightBtmEdt = new QTextEdit(pRightSpliter);
pRightBtmEdt->setText(QObject::tr("Left Bottom Window"));
// 设置左右比为1:4
pSpliter->setStretchFactor(0, 1);
pSpliter->setStretchFactor(1, 4);
pRightSpliter->setStretchFactor(0, 1);//右面窗口上下窗口高度比为1:4
pRightSpliter->setStretchFactor(1, 4);
pSpliter->setWindowTitle(QObject::tr("Split-Wnd Demo2"));
demo3
// 1. 设置一个总的Splitter
QSplitter *pSpliter = new QSplitter(Qt::Horizontal);
//2. 设置 左边的Splitter
QSplitter *pLeftSpliter = new QSplitter(Qt::Vertical);
QTextEdit* pLeftTopEdt = new QTextEdit(pLeftSpliter);
pLeftTopEdt->setText(QObject::tr("Left Top Window"));
QTextEdit* pLeftBtmEdt = new QTextEdit(pLeftSpliter);
pLeftBtmEdt->setText(QObject::tr("Left Bottom Window"));
//3. 设置右边的东西wiget
QTextEdit* pRightEdt = new QTextEdit;
pRightEdt->setText(QObject::tr("Left Window"));
//4. 左右的wiget加入总的Splitter
pSpliter->addWidget(pLeftSpliter);
pSpliter->addWidget(pRightEdt);
// 其他设置
pSpliter->setStretchFactor(0, 4);
pSpliter->setStretchFactor(1, 1);//左右宽度比为4:1
pLeftSpliter->setStretchFactor(0, 4);//左面窗口上下窗口高度比为4:1
pLeftSpliter->setStretchFactor(1, 1);