PDA

View Full Version : QGridLayout: Getting the list of QWidget added



ShaChris23
12th November 2010, 01:54
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 );


Added after 1 29 minutes:

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 * item = layout.itemAt(idx);
if(dynamic_cast<QWidgetItem *>(item)) <-- Note! QWidgetItem, and not QWidget!
item->widget()->hide(); <-- widget() will cast you a QWidget!
}

tbscope
12th November 2010, 06:02
dynamic_cast should be avoided when dealing with QObjects.
Use qobject_cast instead.

nish
12th November 2010, 08:47
dynamic_cast should be avoided when dealing with QObjects.
Use qobject_cast instead.

why so? is dynamic_cast is slower than qobject_cast? I do have RTTI always in my compiler, so given that, can you plz elaborate?