[英]How to position an added widget to a layout based on another widget in the same layout?
在我的 GUI 中,我想根據特定操作觸發的信號以編程方式將QComboBox
添加到verticalLayout
。 以下代碼工作正常,並添加了小部件:
QComboBox* userOptions = new QComboBox();
ui->verticalLayout_13->addWidget(userOptions);
但是,這種方式總是將小部件添加到布局的末尾。
我的問題是:如何將添加的QComboBox
定位到verticalLayout
以與同一布局中的另一個小部件對齊? (即:例如在“Go”按鈕上方)
似乎沒有一種方法可以在您想要的布局中顯式插入一個項目。
你有幾個選擇來實現“困難”的方式:
QLayout::takeAt(int index)
獲取要插入的索引之后的所有項目,插入您的項目,然后插入取回的項目。QLayout
子類,該子類支持在特定索引處插入。 您必須實現幾個功能。 編輯:正如 Kuba Ober 指出的那樣,我的一個遺漏,大多數具體布局實現都支持在特定索引處插入,例如QBoxLayout
派生的插入方法將索引作為參數傳遞。
首先,迭代布局以查找您插入的參考項的索引。 然后使用具體布局的特定小部件插入/添加功能。
由於您可能使用QBoxLayout
,因此您將使用其insertWidget
方法插入小部件。
// https://github.com/KubaO/stackoverflown/tree/master/questions/insert-widget-36746949
#include <QtWidgets>
namespace SO { enum InsertPosition { InsertBefore, InsertAfter }; }
bool insertWidget(QBoxLayout * layout, QWidget * reference, QWidget * widget,
SO::InsertPosition pos = SO::InsertBefore, int stretch = 0,
Qt::Alignment alignment = 0) {
int index = -1;
for (int i = 0; i < layout->count(); ++i)
if (layout->itemAt(i)->widget() == reference) {
index = i;
break;
}
if (index < 0) return false;
if (pos == SO::InsertAfter) index++;
layout->insertWidget(index, widget, stretch, alignment);
return true;
}
可以很容易地為QFormLayout
、 QGridLayout
和QStackedLayout
設計類似的功能。
和一個測試工具:
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget w;
QVBoxLayout l{&w};
QLabel first{"First"};
QLabel second{"Second"};
l.addWidget(&first);
l.addWidget(&second);
insertWidget(&l, &first, new QLabel{"Before First"}, SO::InsertBefore);
insertWidget(&l, &second, new QLabel{"After Second"}, SO::InsertAfter);
w.show();
return app.exec();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.