繁体   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