[英]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. 我正在尝试创建一个类暴露一个QObject派生类的集合(或几个)(具有自己的qt属性)qt属性我可以在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. 根据http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#no-copy-constructor-or-assignment-operator,qt与复制构造函数不兼容。
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. 所以我使用
QList<QObject derived class>
(我的第一个想法)我不能通过引用传递列表(或者至少我认为这是编译器错误所暗示的)(需要副本)并且很难搞清楚如何添加列表中的项目。
Should I use QList<QObject derived class *>
or QList<SomeQTSmartPointer<QObject derived class>>
or something else? 我应该使用
QList<QObject derived class *>
还是QList<SomeQTSmartPointer<QObject derived class>>
或其他什么?
Well, both QList<Derived*>
and QList<std::unique_ptr<Derived>>
will do. 好吧,
QList<Derived*>
和QList<std::unique_ptr<Derived>>
都可以。 If you are using the Qt default garbage collector (with the parent-child tree) you can just use: 如果您使用Qt默认垃圾收集器(使用父子树),您可以使用:
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(...));
Should I use
QList<QObject derived class *>
orQList<SomeQTSmartPointer<QObject derived class>>
or something else?我应该使用
QList<QObject derived class *>
还是QList<SomeQTSmartPointer<QObject derived class>>
或其他什么?
Both are fine, but it is better to stick to the former through the Qt parent/child mechanism in general. 两者都很好,但最好通过Qt父/子机制坚持前者。 This would be the most Qt'ish way of managing it in general:
这将是一般管理它的最Qt'ish方式:
QList<MyClass*> list;
list.append(new MyClass(parent);
You could also use Qt smart pointers like QPointer, QScopedPointer or QSharedPointer as follows: 您还可以使用Qt智能指针,如QPointer,QScopedPointer或QSharedPointer,如下所示:
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. 这适用于pre C ++ 11和post。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.