Suppose I want to implement a model/view architecture using the QTableView
and QAbstractTableModel
classes. So I subclass the QAbstractTableModel
to create class MyModel
and implement the QAbstractTableModel
interface. Then connect the instance of this model to a QTableView
instance using the setModel
method.
#include <QtGui/QApplication>
#include <QtGui/QTableView>
#include "mymodel.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView tableView;
MyModel myModel(0);
tableView.setModel( &myModel );
tableView.show();
return a.exec();
}
But how can I make the model read only? I cannot declare
const MyModel myModel(0);
because setModel takes a non constant argument. I reimplemented only constant methods of QAbstractTableModel.
What do you mean by const
in this case? What do you want to achieve?
Do you want your underlying data to be immutable - so that edition from QTableView
would be impossible? Then just disallow editing the model - e.g. by not implementing setData
.
Also note that the standard implementation of
Qt::ItemFlags QAbstractItemModel::flags ( const QModelIndex & index ) const
will not return Qt::ItemIsEditable
which is sufficient.
You will have to take care not to modify the model outside of the UI (note that modifying it outside without sending appropriate signals can result in bad things). But as it is your code - this shouldn't be an issue.