views:

650

answers:

1

Hi,

I'm doing some refactoring. I'm implementing a Model-View-Controller pattern. The view is a Qt widget.

Originally, the Qt widget created a new instance of a QAbstractTableModel subclass on the heap. Lets call it FooTableModel.

e.g

Widget::Widget(QWidget* parent)
 : 
 QWidget(parent)
 m_model(new FooTableModel(this))
{

Should I create the new instance of FooTableModel in the MVC model instead?

By doing so, I could create a dependency on the view (assuming I still pass the widget's pointer to the FooTableModel constructor)

Alternatively, I could pass nothing to the FooTableModel constructor and manually delete the FooTableModel in my MVC model. *

The last option would be to leave the creation of the FooTableModel in the widget. (And let the widget handle the FooTableModel directly?)

Any suggestions, or preferences?

My guess is to go with * at the moment.

+2  A: 

Generally you want to avoid passing the view to the model.

If your MVC model is a QObject and the FooTableModel instance is a child of it then you don't need to worry about the cleanup becasue Qt will do it for you. Ideally, if you are using Qt the FooTableModel would be THE model, or whatever had the instance of it would be.

Qt follows the Model/View pattern since the controller work is handled by the view. Check out: http://doc.trolltech.com/4.5/model-view-introduction.html for more.

Short answer: Pass nothing to FooTableModel, delete it when done.

Adam W
Thanks for the suggestion. :) My MVC model isn't a QObject, so I'll do the cleanup in its destructor. My MVC model is handling the data for the whole widget, where the FooTableModel is being used for a QTableView that is drawn on the widget. I'll probably stick with this at the moment. "if you are using Qt the FooTableModel would be THE model". Do you mean I should use a Qt model as a model for the whole widget? (Instead of rolling my own) I'm not sure how I would do this. I usually link up a Qt model with its associated view.
Steven
Sorry for the huge delay. Yes ideally you would use have some QAbstractItemModel class as a model for the whole widget. If all your model is doing is storing a reference to a QAbstractItemModel and a few other properties, you could have the class inherit from that model type and store the properties as well. This would allow for more options in the Model/View framework.
Adam W