Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a constant correct read only model/view architecture in Qt?

Tags:

c++

qt

model-view

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.

like image 411
Martin Drozdik Avatar asked Dec 22 '25 11:12

Martin Drozdik


1 Answers

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.

like image 88
Anonymous Avatar answered Dec 24 '25 01:12

Anonymous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!