Search code examples
c++qtqobjectqtcoreqlist

What is the right way for an object to have a collection of a QObject derived class?


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?


Solution

  • 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.