我創建了一個簡單的QHBoxLayout
(水平),它被推到QVBoxLayout
(垂直)的底部,它包含兩個按鈕。請參閱代碼:Qt佈局,傳遞和不傳遞QWidget作爲父項的差異
QWidget* create_ver_and_horizontal_box() {
QWidget* temp = new QWidget();
// Add buttons to the horizontal box
QHBoxLayout* hbox = new QHBoxLayout();
QPushButton *ok = new QPushButton("OK");
QPushButton *cancel = new QPushButton("Cancel");
hbox->addWidget(ok);
hbox->addWidget(cancel);
// Create a vertical box and add the horizontal box to
// the end of it
QVBoxLayout* vbox = new QVBoxLayout();
vbox->addStretch(1);
vbox->addLayout(hbox);
// set the layout and return
temp->setLayout(vbox);
return temp;
}
但是當我添加QWidget的temp
是QHBoxLayout,負責的父母,就像這樣:
// Add buttons to the horizontal box
QHBoxLayout* hbox = new QHBoxLayout(temp);
我想明白是怎麼回事在這。在這種情況下,我希望QWidget成爲佈局或任何其他QWidget的父項,並且在這種情況下,我不會將包含QWidget作爲包含QWidgets的父項。例如,我可以添加temp作爲兩個按鈕的父項,但我沒有。不添加vs添加的含義是什麼?
謝謝,
Qt佈局會爲您管理父母,他們將通過調用'addWidget()/ addLayout()'來正確設置/更新。在第二種情況下,創建的對象'vbox'不會在任何地方使用(只有hbox),因此這些按鈕被放置在水平佈局中。垂直居中是'QHBoxLayout'的默認行爲。 – Radek