问题
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?
回答1:
Should I use
QList<QObject derived class *>
orQList<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.
回答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(...));
来源:https://stackoverflow.com/questions/21120458/what-is-the-right-way-for-an-object-to-have-a-collection-of-a-qobject-derived-cl