Qt拆分窗口可以使用QSplitter,也可以使用比较容易使用布局控件来完成,本文章给出使用QSplitter分割窗口的例子。
QSplitter 继承自QFrame,而QFrame又继承自QWidget,这点很重要。
对于使用QSplitter拆分窗口:
- 新建一个QSplitter,就意味着新建了一个QWidget
- 不同的QSplitter对象通过指定父子关系来完成嵌套(划分窗口)
- QSplitter可以放置到你指定的任何窗口内
样例1
核心代码如下:
qDebug("Mainframe start...
");
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);
pSpliter->setWindowTitle(QObject::tr("Split-Wnd Demo1"));
pSpliter->show();
需要添加的头文件如下:
#include <QSplitter>
#include <QTextEdit>
样例2
核心代码如下:
qDebug("Mainframe start...
");
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"));
pSpliter->show();
需要添加的头文件如下:
#include <QSplitter>
#include <QTextEdit>
样列3
核心代码:
qDebug("Mainframe start...
");
// 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);
pSpliter->setWindowTitle(QObject::tr("Split-Wnd Demo3"));
pSpliter->show();
需要添加的头文件如下:
#include <QSplitter>
#include <QTextEdit>