Qt之基礎佈局(QBoxLayout)

簡述

Qt提供了QBoxLayout用來將控件進行水平或垂直佈局,QHBoxLayout和QVBoxLayout是QBoxLayout的兩個子類,使用起來更方便一點。

QHBoxLayout和QVBoxLayout的使用方法差不多,我們以QVBoxLayout爲例進行介紹。

用法

下面介紹基本使用方法

效果

源碼

    QPushButton *button1 = new QPushButton("One");
    QPushButton *button2 = new QPushButton("Two");
    QPushButton *button3 = new QPushButton("Three");
    QPushButton *button4 = new QPushButton("Four");
    QPushButton *button5 = new QPushButton("Five");

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
    layout->addWidget(button4);
    layout->addWidget(button5);

    this->setLayout(layout);

常見操作

  • 設置外邊距
    • setMargin(int)
    • setContentsMargins(int left, int top, int right, int bottom);
    • setContentsMargins(const QMargins &margins)

setMargin以像素爲單位同時設置左右上下邊距(新版本Qt不建議使用)。

setContentsMargins以像素爲單位分別設置左右上下邊距。

這裏我設置setContentsMargins(5, 0, 20, 0),效果如下:

  • 設置控件間距
    • setSpacing(int)

我們可以通過setSpacing來設置佈局內控件的間距。

如果這個值沒有被設置,佈局的間距屬性會繼承自父佈局或者是父控件的樣式表。

我們用setSpacing(0)設置控件間距爲0,如下所示:

  • 添加伸縮空間
    • addStretch()

居下

在所有控件之前加

    layout->addStretch();
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
    layout->addWidget(button4);
    layout->addWidget(button5);

居上同理,在所有控件之後加addStretch

  • 控件對齊
    • Qt::Alignment

有時候控件並不是完全一樣的,如下所示

我們現在希望Three靠右邊排布,可以通過如下方式實現

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3, 0, Qt::AlignRight);
    layout->addWidget(button4);
    layout->addWidget(button5);
  • 設置控件、佈局的伸展因子
    • setStretchFactor(QWidget *w, int stretch);
    • setStretchFactor(QLayout *l, int stretch);

當窗體大小變化時,控件會根據拉伸係數來做相應的調整。

    QPushButton *button1 = new QPushButton("One");
    button1->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    QPushButton *button2 = new QPushButton("Two");
    button2->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    QPushButton *button3 = new QPushButton("Three");
    QPushButton *button4 = new QPushButton("Four");
    QPushButton *button5 = new QPushButton("Five");

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
    layout->addWidget(button4);
    layout->addWidget(button5);

    layout->setStretchFactor(button1, 3);
    layout->setStretchFactor(button2, 1);

總結


上面介紹了一些常用的接口,其它的可以自己看手冊

reference
[1] Qt助手

[2] https://blog.csdn.net/liang19890820/article/details/51537246

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章