qtqtableviewqabstracttablemodel

How to set data inside a QAbstractTableModel


I need to implement a table with Qt.

I believe I'll be suing a QAbstractTableModel, with a QTableView using this model.

I understand I'll have to edit the rowCount(), columnCount(), and data() functions of the model.

However, I don't understand how to exactly set the data inside the model, so that data() function can retrieve it..

Is the setData() function provided for this purpose? I have seen it takes EditRole as its parameter, which I don't want, as I don't want my table to be editable.

So, how do I "set" data inside the model, or have data for the model to get at, using data() function?

Also, how is the data() function called, i.e., who calls it and where would it need to be called?

Please help me with this.

Thanks.


Solution

  • How the actual data is kept in memory, generated or queried from a data store is completely up to you. If it's static data, you can use the Qt container classes or custom data structures.

    You only need to reimplement the setData() method for editable models.

    There are 4 methods you need to implement in a non-editable QAbstractTableModel subclass:

    These methods are called from the view, usually a QTableView instance. The first two methods should return the dimensions of the table. For example, if rowCount() returns 10 and columnCount() returns 4, the view will invoke the data() method 40 times (once for each cell) asking for the actual data in your model's internal data structures.

    As an example suppose you have implemented a custom slot retrieveDataFromMarsCuriosity() in your model. This slot populates a data structure and is connected to a QPushButton instance, so you get fresh data by clicking a button. Now, you need to let the view know when the data is being changed so it can update properly. That's why you need to emit the beginRemoveRows(), endRemoveRows(), beginInsertRows(), endInsertRows() and its column counterparts.

    The Qt Documentation has everything you need to know about this.