PDA

View Full Version : QComboBox setModel - ownership???



lotek
4th August 2011, 22:25
Hello,

Does QComboBox own the model after setting it with setModel();

Manual says no word about it.

Thx

Talei
5th August 2011, 01:10
Check it for Yourself, i.e.:


QComboBox *cb = new QComboBox( this );
QStandardItemModel *model = new QStandardItemModel(this);

qDebug() << model->parent();
cb->setModel( model );
qDebug() << model->parent();

So basically no, views don't take ownership of model, unless explicitly set, because they can be shared by many views.

Also there is an error in man.:

The view does not take ownership of the model unless it is the model's parent object because the view (should be model?) may be shared between many different views.

lotek
5th August 2011, 09:57
Check it for Yourself, i.e.:


QComboBox *cb = new QComboBox( this );
QStandardItemModel *model = new QStandardItemModel(this);

qDebug() << model->parent();
cb->setModel( model );
qDebug() << model->parent();

So basically no, views don't take ownership of model, unless explicitly set, because they can be shared by many views.

Also there is an error in man.:

Hallo,

Thanks for the answer.

For deletion it means: first the view, than the model - correct?
By the way, is the parenthood this same as ownership? I.e. does a parent widget automatically delete its all children when destroyed?

Talei
5th August 2011, 16:37
Please RTM :)
Look here : http://doc.qt.nokia.com/4.7/objecttrees.html and http://doc.qt.nokia.com/4.7/qt-basic-concepts.html

Basically any new object that is QObject subclass uses parent/child relationship. This means that if parent is deleted all children are deleted to.
In above example it you delete "this' then model and view will be deleted to.
If you write above code like this:


QComboBox *cb = new QComboBox( this );
QStandardItemModel *model = new QStandardItemModel( cb );

qDebug() << model->parent();
cb->setModel( model );
qDebug() << model->parent();

delete cb;
deleting cb will delete model also.
Althought if You delete model from view then view don't "know" what/how to display. By default views i.e. QComboBox creates QStandardItemModel in constructor so after You delete Your custom model You will have to add new one, something along this line's:

QComboBox *cb = new QComboBox( this );
QStandardItemModel *model = new QStandardItemModel( cb );
model->setObjectName( "My Old model" );

qDebug() << model->parent();
cb->setModel( model );
qDebug() << model->parent();

delete model;
cb->setModel( new QStandardItemModel(0, 1, cb) );
cb->model()->setObjectName( "New model" );
cb->addItem( "sample", "Sample" );
qDebug() << "Model name:" << cb->model()->objectName() << "Parent: " << cb->model()->parent();