PDA

View Full Version : Dynamic objects without identifier...



Bill
10th August 2009, 17:34
Hi,
I'm facing a problem which I can't overcome... In a for() loop I'm creating objects of 3 different classes depending on an if() statement:



if(type == "string")
{
QLineEdit *string = new QLineEdit(groupBox);
groupBox->layout()->addWidget(string);
}
else if(type == "date")
{
QDateEdit *date = new QDateEdit(groupBox);
groupBox->layout()->addWidget(date);
}
else if(type == "image")
{
QLabel *image = new QLabel("image",groupBox);
groupBox->layout()->addWidget(image);
}


Now it would be nice to have some sort of array of those objects with an ID key, so I can lookup a specific object depending on the ID and change it's contents. I've tried QHash, but I would end up with 3 or more class fields of type QHash<int, className*>.

Do you have any better suggestion?
Thanks in advance,
Regards,

Bill

wysota
11th August 2009, 23:09
QHash<int, QWidget*> and qobject_cast to determine the type.

Bill
12th August 2009, 09:03
Hi,
Thanks for your reply. I've decided to use a QObjectList which I populate in the if statements, where additionally I set the proper object names used later to identify the object "type" (image, string etc.). Works pretty well.

Regards,
Bill

wysota
12th August 2009, 09:25
It might be better to use QList<QWidget*> - it's better for you than QList<QObject*> because you can use the widget interface without any casting. If you want to stick with QObjectList, then you don't need it at all - at any time you can call QObject::children() on the parent widget (or the layout - you'd have to check that out) that will return you a QObjectList of its children.

axeljaeger
13th August 2009, 10:10
QList<QString, QMetaObject>. Store the classes meta objects and then use QMetaObject::newInstance to create new instances.

Bill
17th August 2009, 17:48
Hi,
Thanks for the QMetaObject hint - I'll look at it in detail...
Another problem I have is that I create an object and add it to a QScrollArea like this:


scrollAreaWidgetContents->layout()->addWidget(date);


What would be the best way to remove objects from the QScrollArea, which have a pointer stored in a QList<QWidget*>?
I've tried


for(int i=0;i<formElements.length();++i) scrollAreaWidgetContents->layout()->removeWidget(formElements.at(i));

but end up with a segfault.

Thanks for your help,
Reagards,
Bill

Bill
18th August 2009, 14:37
I think I found a solution.
After a bit of RTFM,


while(!formElements.isEmpty()) delete formElements.takeFirst();


works well.

Regards,
Bill

axeljaeger
18th August 2009, 15:17
Does qDeleteAll works as well?