0
votes

I'm trying to use QObject tree delete mechanism to delete the list and all QObjects that are stored in the list. Qt is still my very week area...

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? Doesn't it inherit from QObject?

Edit:

The main question - is it possible to conveniently delete the list and all list elements without extending the QList class? 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;
2
The biggest question is why are you dynamically allocating the whole list at all. Why it isn't just a QList<QObject*> list?Jan Kundrát
Not possible with QList<QObject*> - you could use QSharedPointer though.Frank Osterfeld

2 Answers

1
votes

No. QList does not inherit from QObject. If you want to delete the contents of the list easily, you can use 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 ); }
 }
0
votes

option 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)

 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:

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