如何将项添加到布局中的特定索引

时间:2013-07-22 10:54:17

标签: qt

我按照这个例子创建了一个Flow布局:

http://doc.qt.io/qt-4.8/qt-layouts-flowlayout-example.html

这没有addToIndex(int _index)函数,所以我想实现它。由于此布局使用QLayoutItems,我想创建一个可以在特定索引后插入Item的函数。

如何将Item的索引作为整数并插入布局?

更新:

flowlayout.cpp

FlowLayout *flowLayout = new FlowLayout;
void FlowLayout::insertItem(int index, QLayoutItem *item) 
{
   if(itemList.size() < index)
   {
     itemList.append(item);
   }
   else
   {
     itemList.insert(index,item);
     QRect tmp = this->geometry();
   }
   update();
}

flowwindow.cpp

void FlowWindow::addLineBreak()
{

  flowbreak = new FlowLayoutButton(NULL);

  QLayoutItem *item = new QWidgetItem(flowbreak);
  flowlayout->insertItem(index, item);
  //flowlayout->addWidget(flowbreak);

}

flowlayoutbutton.cpp构造函数

 FlowLayoutButton::FlowLayoutButton(QWidget *_parent):QWidget(_parent)
 {
  QBoxLayout *layout = new QHBoxLayout;


  flowbreak = new QPushButton(tr("-------Label-------"));
  flowbreak->setGeometry(0, 0, 200,20);
  layout->addWidget(flowBreak);

  setLayout(layout);
}

1 个答案:

答案 0 :(得分:1)

添加以下方法:

flowlayout.h:

class FlowLayout : public QLayout
{
public:
   void insertWidget(int index, QWidget *w);
   // rest of the class from the example
};

flowlayout.cpp:

// new method
void FlowLayout::insertWidget(int index, QWidget *w) {
   addWidget(w);
   itemList.move(indexOf(w), index);
}

现在你可以通过调用来使用它(假设你有一个指向名为flowLayout的布局的指针):

flowLayout->insertWidget(2,new QPushButton("Button"));
相关问题