1. 程式人生 > >QT 之QSplitter 切割視窗

QT 之QSplitter 切割視窗

QT之切分視窗

     QSplitter就是一個可以包含一些其他視窗部件的部件。在切分視窗QSplitter中的這些視窗部件會通過切分條Splitter handle而分割開來。使用者可以通過拖動這些分割條改變切分條中子視窗的大小。QSplitter中的子視窗部件將會自動按照建立時的順序一個挨著一個的放在一起,並且以切分視窗分割條來分割相鄰的視窗。下面是程式碼例項

#include <QtGui>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QTextEdit *editor1 = new QTextEdit;    //定於在splitter中的三個編輯框

    QTextEdit *editor2 = new QTextEdit;
    QTextEdit *editor3 = new QTextEdit;
    QSplitter splitter(Qt::Horizontal);        //定義一個切分視窗
   splitter.addWidget(editor1);               //將檔案控制元件加入到切分框
    splitter.addWidget(editor2);
    splitter.addWidget(editor3);        
    editor1->setPlainText("Mon enfant, ma soeur,\n"

                          "Songe  la douceur\n"
                          "D'aller l-bas vivre ensemble,\n"
                          "Aimer  loisir,\n"
                          "Aimer et mourir\n"
                          "Au pays qui te ressemble.");
    editor2->setPlainText("My child, my sister,\n"

                          "think of the sweetness\n"
                          "of going there to live together!\n"
                          "To love at leisure,\n"
                          "to love and to die\n"
                          "in a country that is the image of you!");
    editor3->setPlainText("Mein Kind, meine Schwester,\n"
                          "denke an den Traum\n"
                          "dort hin(unter) zu gehen um zusammen\n"
                          "zu leben und in aller Ruhe zu lieben,\n"
                          "Zu lieben und zu sterben\n"
                          "in dem Land, das dir gleicht.");
    splitter.setWindowTitle(QObject::tr("Splitter"));          //設定標題
    splitter.show();
    return app.exec();

}

效果如下:

可以隨意改變各個視窗大小:

另外下面演示下使用多個splitter進行水平或者垂直方向上的巢狀。本程式碼適用於《C++ GUI QT4》

mailclient.cpp. 其介面佈局部分程式碼如下

//窗口布局
    rightSplitter = new QSplitter(Qt::Vertical);
    rightSplitter->addWidget(messagesTreeWidget);  //在右視窗中新增一個郵件列表
    rightSplitter->addWidget(textEdit);                         //顯示文字郵件
    rightSplitter->setStretchFactor(1, 1);                      //保證textEdit伸展到多餘的空間
    mainSplitter = new QSplitter(Qt::Horizontal);
    mainSplitter->addWidget(foldersTreeWidget);
    mainSplitter->addWidget(rightSplitter);
    mainSplitter->setStretchFactor(1, 1);                     //使用兩個setStretchFactor保證了把多餘的額外空間都留給textEdit
    setCentralWidget(mainSplitter);
    setWindowTitle(tr("Mail Client"));

效果如下圖: