Qt Layout Management

來源:互聯網
上載者:User
Horizontal、Vertical、Grid Layouts

首先介紹最簡單的版面配置方法,那就是使用Qt提供的基本的版面組態管理:QHBoxLayout、QVBoxLayout與
QGridLayout。

這些類別是繼承自QLayout類別(再繼承自QObject類別)。這些類別主要負責widget版面位置的管理,經由這些版
面配置處理

可以產生更複雜的版面配置。

 

  • QHBoxLayout將widget編排成水平的一列:

下列的程式碼建立一個QHBoxLayout,將5個QPushButton放置其中,其結果如圖所示:

QWidget *window = new QWidget;
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");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
layout->addWidget(button4);
layout->addWidget(button5);
window->setLayout(layout);
window->show();

 

  • QVBoxLayout將widget編排成為垂直的一行:

QVBoxLayout的程式碼與上述的QHBoxLayout類似,其產生的結果如下:

 

  • QGridLayout將widget編排成為二維的格子狀,widget可以佔據多個格子:

而使用QGridLayout則有些微不同,因為必須要指定widget的行與列位置。

QWidget *window = new QWidget;
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");
QGridLayout *layout = new QGridLayout;
layout->addWidget(button1, 0, 0);
layout->addWidget(button2, 0, 1);
layout->addWidget(button3, 1, 0, 1, 2);
layout->addWidget(button4, 2, 0);
layout->addWidget(button5, 2, 1);
window->setLayout(layout);
window->show();

第三個QPushButton佔據了2行,所以在QGridLayout::addWidget()中指定了第五個參數2。
使用這種版面配置,

對child widget做版面配置時將不需要將parent widget參數引進來,此版面配置會自動利用QWidget::setParent()把Parent widget傳進來。

當使用者使用某個layout於這個視窗應用程式,而在這個layout中加入其他widget(譬如上例中的PushButton),則這些widget都自動成
為那個視窗應用程式使用此layout的child widget(記住,widget不能繼承自layout,只有widget之間才行)。

此外,你可以利用addLayout()在版面配置中再加入其他版面配置;addLayout()中加入的版面配置就會成為外面版面配置的child,

即可形成更複雜的版面配置。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.