假设我有类似的东西:
QGridLayout layout;
layout.addWidget(new QWidget());
layout.addWidget(new QWidget());
我可以用什么方法来获取添加的QWidgets列表?
像下面虚构的getAddedWidgets()
:
QList<QWidget*> addedWidgets = layout.getAddedWidgets();
Q_ASSERT( addedWidgets.size() == 2 );
答案 0 :(得分:6)
下面的示例代码显示了如何迭代对每个项目进行操作:
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();
}