3

I'm trying to make a class exposing a collection(or several) of a QObject derived class(with its own qt properties) qt properties I can use in qml.

According to http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#no-copy-constructor-or-assignment-operator qt doesn't play well with copy constructors.

So I used QList<QObject derived class> (my first idea) I can't pass the list by reference(or at least I think thats what the compiler errors implies)(needs copies) and am having a hard time figuring out howto add items to the list.

Should I use QList<QObject derived class *> or QList<SomeQTSmartPointer<QObject derived class>> or something else?

László Papp
  • 51,870
  • 39
  • 111
  • 135
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141

2 Answers2

2

Well, both QList<Derived*> and QList<std::unique_ptr<Derived>> will do. If you are using the Qt default garbage collector (with the parent-child tree) you can just use:

QList<Derived*> list;
list.push_back(new Other(parent, ...));

otherwise you should use the second:

QList<std::unique_ptr<Derived>> list;
list.push_back(new Other(...));
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • One can also use `QList >`. – Kuba hasn't forgotten Monica Jan 14 '14 at 18:17
  • "It should be noted that in the first case, it should read new Other(parent)" -> Not necessarily. It depends on the constructor definition of the derived class. "One can also use QList >" -> Yes, as well as QSharedPointer, QPointer, etc... – László Papp Jan 14 '14 at 19:39
  • Jeffrey, my concern is that with your answer, it is formed towards C++11 (unique pointer, push back instead of append, and >>, too, without space) as opposed to a Qt solution for pre C++11 and post where Qt is supposed to work. I will not downvote though because I think both could be useful for the readers. Hope, you do not mind my answer. :) – László Papp Jan 14 '14 at 19:45
2

Should I use QList<QObject derived class *> or QList<SomeQTSmartPointer<QObject derived class>> or something else?

Both are fine, but it is better to stick to the former through the Qt parent/child mechanism in general. This would be the most Qt'ish way of managing it in general:

QList<MyClass*> list;
list.append(new MyClass(parent);

You could also use Qt smart pointers like QPointer, QScopedPointer or QSharedPointer as follows:

QList<QShardPointer<MyClass> > list;
// Being explicit to be more comprehensive, but it is not necessary
list.append(QSharedPointer<MyClass>(new MyClass());

This will work with both pre C++11 and post.

Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141
László Papp
  • 51,870
  • 39
  • 111
  • 135