QGridLayout

QGridLayout為網格的布局管理員,在setMargin()、setSpacing()、addStretch()等使用方式都和QHBoxLayout相同,但在addWidget()時可指定widget的位置及佔位幾列幾行,這邊示範用QGridLayout建構一個輸入表單。


dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QLineEdit>
#include <QComboBox>
#include <QTextEdit>
#include <QGridLayout>
#include <QFrame>
#include <QLabel>

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
private:
    QLabel *nameLabel;
    QLabel *sexLabel;
    QLabel *departmentLabel;
    QLabel *otherLabel;
    QLineEdit *nameLineEdit;
    QComboBox *sexComboBox;
    QTextEdit *departmentTextEdit;
    QLineEdit *otherLineEdit;
    QGridLayout *infoLayout;
};

#endif 

dialog.cpp

#include "dialog.h"

Dialog::Dialog(QWidget *parent)
    :QDialog(parent)
{
   setWindowTitle(tr("個人資訊"));
   nameLabel = new QLabel(tr("姓名:"));
   nameLineEdit = new QLineEdit;
   sexLabel = new QLabel(tr("性別:"));
   sexComboBox = new QComboBox;
   sexComboBox->addItem(tr("女"));
   sexComboBox->addItem(tr("男"));
   departmentLabel = new QLabel(tr("部門:"));
   departmentTextEdit = new QTextEdit;
   otherLabel = new QLabel(tr("備註:這是個人資料表"));

   infoLayout = new QGridLayout(this);
   infoLayout->addWidget(nameLabel,1,0);
   infoLayout->addWidget(nameLineEdit,1,1);

   infoLayout->addWidget(sexLabel,2,0);
   infoLayout->addWidget(sexComboBox,2,1);

   infoLayout->addWidget(departmentLabel,3,0);
   infoLayout->addWidget(departmentTextEdit,3,1);

   infoLayout->addWidget(otherLabel,5,0,1,2); //後面兩個參數表示此物件佔空間1列2行,

   infoLayout->setColumnStretch(0,1);  //框架大小改變寬度比例保持不變
   infoLayout->setColumnStretch(1,4);  //第1行佔比例為1,第2行佔比例為4
   infoLayout->setMargin(10);          //設定邊距為10
   infoLayout->setSpacing(10);         //設定元件間的距離為10
}

dialog.cpp

#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();

}

QGridLayout