簡體   English   中英

如何根據同一布局中的另一個小部件將添加的小部件定位到布局中?

[英]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;
}

可以很容易地為QFormLayoutQGridLayoutQStackedLayout設計類似的功能。

和一個測試工具:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM