PDA

View Full Version : How to save Child if Parent Object is deleted.



vaibhav
25th May 2011, 07:48
Hi,

I'm trying to maintain strong references to Qt objects in my application.

Given the following code snippet:

// ...
QWidget bar;
QLabel* foo = new QLabel(&bar);
// ...

'bar' now owns 'foo' and is responsible for deleting it. Now I know that the following is valid:

// ...
QWidget bar;
QLabel* foo = new QLabel(&bar);
delete foo;
// ...

Because in 'foo's destructor it removes itself from its parent's to-delete list.

But the problem is that - given a parent's child was not deleted - whenever the parent is destroyed it destroys its children and any external references to the children in the application become dangling pointers.

So what I need is something that tells the parent that there are still external references to the children, so it should not delete them. Since widgets don't inherit from QSharedData, I have no idea how to do this.

Not setting parents is not an option, because in that case, widgets don't appear inside other widgets, since there is no relation between them.

Please help me to find a solution to this.

Santosh Reddy
25th May 2011, 07:58
Why do you maintain the child widget's pointer when the parent no more exists?

vaibhav
25th May 2011, 08:10
That is required in my application.Where those references to child in mainted in some other class.

Santosh Reddy
25th May 2011, 08:20
Do the the references maintained in some other class need to be QWidget type? if not then you may think of having a Class whose reference / pointer in maintained by you, and then connect to this class to the child QWidget. This way even if the child widget is deleted, you still have the your class object, with which you can work.

Just as a suggestion:
As I understand, you may be trying to have a custom widget, with some custom data in it, and when the widget is deleted, you lose you data in there. It is better to keep you data components and GUI components separated, mixing them them in a class will give complications in long run, as the program grows

vaibhav
25th May 2011, 08:28
I didn't completely get you but my problem is excatly the same as told by you .

I am Adding some QWidget in my QFiledialog's layout.
When my QFileDialog is deleted it delets that Qwidget which i am using in my application.

Could you detail me more on my problem.

Santosh Reddy
25th May 2011, 08:38
So, you may need to create another widget for the QFileDialog, and not use the one used by application. Also as required by your logic, you may transfer data between the application widget and QFileDialog widget

stampede
25th May 2011, 08:52
If you really want to do it your way, then reimplement the QFileDialog destructor, and call yourSharedWidget->setParent(NULL); there, this way the widget will be removed from children list, and not deleted. But I agree with Santosh Reddy, maybe you should rethink the design.