2

Is there a Qt container, that is aware of the destroyed signal of QObject and removes the element if an element was destroyed?

I.e. like this:

QObject *obj1 = new MyObject();
QObject *obj2 = new MyObject();
QObjectContainer c;
c.add(obj1);
c.add(obj2);
qDebug() << c.size(); // Prints 2
delete obj1;
qDebug() << c.size(); // Prints 1
sashoalm
  • 75,001
  • 122
  • 434
  • 781
ManuelSchneid3r
  • 15,850
  • 12
  • 65
  • 103
  • Wait, you have a flaw in your idea. If you delete an object, how would you find its index in the array? You'd need to perform a full search each time. Think about it, it can't be implemented in any reasonable way. Even if your array catches the `destroyed()` signal, it gets only the address of the pointer, not its index in the array. You'll need to search it by value. The performance would be awful. – sashoalm Mar 17 '15 at 13:44
  • Add your objects as children of a dummy parent QObject ;-) – peppe Mar 17 '15 at 21:50

2 Answers2

1

You can do it yourself by catching signal destroyed() inside container-derived class.

P.S. No Qt class does this, AFAIK.

Matt
  • 13,674
  • 1
  • 18
  • 27
0

QPointer will auto clear itself when the object pointed to is deleted

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • Well thats fine bit is there a list which will remove the QPointer if the contained object pointed to is deleted. – ManuelSchneid3r Mar 17 '15 at 12:29
  • @ManuelSchneid3r you can do some bookkeeping during iteration, though a indexed list is probably not a good idea instead a set-like container would be better. – ratchet freak Mar 17 '15 at 12:31