简体   繁体   English

QObject使用setParent()将QList设置为父级

[英]QObject set QList as parent using setParent()

I'm trying to use QObject tree delete mechanism to delete the list and all QObject s that are stored in the list. 我正在尝试使用QObject树删除机制来删除列表以及存储在列表中的所有QObject Qt is still my very week area... Qt仍然是我每周的工作区域...

QList<QObject*>* list = new QList<QObject*>();
QObject* obj1 = new QObject();
QObject* obj2 = new QObject();
obj1->setParent(obj2);
obj2->setParent((QObject*)list);

I got "Segmentation fault" at last line. 我在最后一行收到“细分错误”。 Can't the QList be used as a parent? QList不能用作父项吗? Doesn't it inherit from QObject ? 它不是从QObject继承吗?

Edit : 编辑

The main question - is it possible to conveniently delete the list and all list elements without extending the QList class? 主要问题-是否可以在不扩展QList类的情况下方便地删除列表和所有列表元素? This need to be called by client so it have to be simple. 这需要由客户端调用,因此必须简单。

I would like to simply call: 我想简单地打电话给:

delete list;

and not 并不是

qDeleteAll(list);
delete list;

No. QList does not inherit from QObject . 不可以QList不能从QObject继承。 If you want to delete the contents of the list easily, you can use qDeleteAll(list) . 如果要轻松删除列表的内容,可以使用qDeleteAll(list)

Edit: This is untested, and there may be problems from the base class not having a virtual destructor - but give it ago. 编辑:这未经测试,并且可能有没有虚拟析构函数的基类的问题-但要提前给出。

template < class T >
class MyList : public QList< T >
{
    static_assert( std::is_pointer< T >::value,
                   "T must be a pointer." );
    //  Constructors...
    ...
    virtual ~MyList() { qDeleteAll( *this ); }
 }

option 1) 选项1)

QList<QObject*> list;

.. somewhere in the code

QObject * obj = new QObject();
list << obj;

... 

then 


onDelete() {    // variant 1
       QObject * ptr;
       foreach(ptr, list) {
          delete ptr;
       }
       list(clear);
}

onDelete() { // variant 2
     qDeleteAll(list);
}

option 2) 选项2)

 QObject * parent = new QObject();

 somewhere in a code 
 ...
 QObject * child1 = new QObject(parent);
 QObject * child2 = new QObject(parent);


 onDelete() {
     delete parent;   // all children deleted automatically
 }

UPD: UPD:

From your question update, I can consider that you don't QList at all, just use QObject provided functionality, and if you need children use appropriate childer() method which will give you QList 从您的问题更新中,我可以认为您根本就没有QList,只需使用QObject提供的功能,如果需要子项,请使用适当的childer()方法,该方法将为您提供QList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM