2017-03-03 12 views
0

我創建了一個簡單的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; 
} 

以及生成的UI如下。 enter image description here

但是當我添加QWidget的temp是QHBoxLayout,負責的父母,就像這樣:

// Add buttons to the horizontal box 
    QHBoxLayout* hbox = new QHBoxLayout(temp); 

這就是我得到: enter image description here

我想明白是怎麼回事在這。在這種情況下,我希望QWidget成爲佈局或任何其他QWidget的父項,並且在這種情況下,我不會將包含QWidget作爲包含QWidgets的父項。例如,我可以添加temp作爲兩個按鈕的父項,但我沒有。不添加vs添加的含義是什麼?

謝謝,

+0

Qt佈局會爲您管理父母,他們將通過調用'addWidget()/ addLayout()'來正確設置/更新。在第二種情況下,創建的對象'vbox'不會在任何地方使用(只有hbox),因此這些按鈕被放置在水平佈局中。垂直居中是'QHBoxLayout'的默認行爲。 – Radek

回答

2
QHBoxLayout* hbox = new QHBoxLayout(temp); 

相當於

QHBoxLayout* hbox = new QHBoxLayout(); 
temp->setLayout(hbox); 

即您正在對temp負責水平佈局。

setLayout(vbox)的調用應產生運行時警告消息,該temp已經有一個佈局,暗示在那。

由於您希望垂直佈局負責該窗口小部件,請保留temp->setLayout(vbox)或將temp傳遞給QVBoxLayout的構造函數。

+0

這很有意義,謝謝你清理那個。 – ArmenB