1

Suppose I have something like:

QGridLayout layout;
layout.addWidget(new QWidget());
layout.addWidget(new QWidget());

What is the method that I can use to get the list of the added QWidgets ?

Something like the imaginary getAddedWidgets() below:

QList<QWidget*> addedWidgets = layout.getAddedWidgets(); 
Q_ASSERT( addedWidgets.size() == 2 );
sivabudh
  • 31,807
  • 63
  • 162
  • 228

1 Answers1

7

The example code below shows how you could iterate over each item:

  QGridLayout layout;

  // add 3 items to layout
  layout.addItem(new QSpacerItem(2,3), 0, 0, 1, 1);
  layout.addWidget(new QWidget);
  layout.addWidget(new QWidget);

  // sanity checks
  Q_ASSERT(layout.count() == 3);
  Q_ASSERT(layout.itemAt(0));
  Q_ASSERT(layout.itemAt(1));
  Q_ASSERT(layout.itemAt(2));
  Q_ASSERT(layout.itemAt(3) == NULL);

  // iterate over each, only looking for QWidgetItem
  for(int idx = 0; idx < layout.count(); idx++)
  {
    QLayoutItem * const item = layout.itemAt(idx);
    if(dynamic_cast<QWidgetItem *>(item))       <-- Note! QWidgetItem, and not QWidget!
      item->widget()->hide();                   <-- widget() will cast you a QWidget!
  }

  // without using RTTI !
  for(int idx = 0; idx < layout.count(); idx++)
  {
    QLayoutItem * const item = layout.itemAt(idx);
    if(qobject_cast<QWidgetItem *>(item))       <-- Qt way of cast! No RTTI required!
      item->widget()->hide();
  }
sivabudh
  • 31,807
  • 63
  • 162
  • 228
  • Good God! I wasted one day trying so many methods to delete a particular widget from my `QBoxLayout`! None of them worked, until I found this! Calling `delete widget` above works perfectly fine.. – SexyBeast Apr 07 '15 at 14:52
  • I believe this does not work anymore as-is. I had to replace item with `item->widget()` (if you do this, don't forget to check the pointer exists). – quimnuss Jan 12 '16 at 17:41