PDA

View Full Version : QObject subclass in a QList



plan_rich
21st September 2010, 11:17
Hi!

I recently programmed some qt and stumbled over the problem, that i cannot add my own class derived from QObject into a QList.

See two examples in attachments!

This code is not very useful but it was just a test to make sure that i made something wrong!

Dog is a simple class with 1 function.
When it is a normal class then i can add it to my QList without a problem.
But if i extend dog from QObject i cannot add it to a QList!

Can someone help me?

I used cmake to compile my examples!

JohannesMunk
21st September 2010, 12:02
Read the docs about QList (http://doc.trolltech.com/latest/qlist.html).

Somewhere soon you will find:

"QList's value type must be an assignable data type. This covers most data types that are commonly used, but the compiler won't let you, for example, store a QWidget as a value; instead, store a QWidget *.

So you need to use the list like this:


QList<Dog*> list;
Dog* dog = new Dog();
list.append(dog);

HIH

Joh

plan_rich
21st September 2010, 15:50
Thx for you fast replay.

And what about memory of the QList<*> ?
Do i have to manage memory of the QList's data?

Can someone give me a guide about memory management of Qt? So do i have to delete pointers of QObjects or not?

Rich

JohannesMunk
21st September 2010, 16:51
You have to delete everything yourself, except that QObject deletes all its children itself.

So for example when you add a widget to a layout, the layout becomes parent of that widget and deletes the widget when it is destroyed.

But you need to delete your custom objects yourself.

Your list will probably be a member variable of some object. in its destructor you call:


// iterates through all items of the list and calls delete on them, but does not remove the entry from the list!
qDeleteAll(list);
// removes all entries from the list.
list.clear();

Joh