driftwood
driftwood

Reputation: 2121

I don't understand how QAbstractItemModel works

I've been using this class somewhat successfully thus far but I feel like I don't have a good conceptual understanding of what I'm doing. I'm missing something basic about the Qt model/view architecture which prevents me from making full use of it. Qt doc doesn't seem to be addressing my questions. Much of my lack of understanding seems to be centered around the data() method.

For example: 1) The doc doesn't properly explain (or I missed it) what the data() method is and how to properly use it. I just have this vague idea that it is some kind of callback or slot function for when there are any changes to my model. But architecturally speaking what is its role? Why is it needed and what problem is it solving?

2) Speaking of roles, what is the point of the role parameter in the data method. Again, why did the designers choose to implement the data() method this way?

I hope my questions aren't too abstract. If they are it might be because I don't fully understand what I don't understand about the model/view architecture. Therefore not quite sure how to formulate my question.

Anyway, anyone who has some decent understanding of these concepts is welcome to chime in. Also if anybody knows other places that explains this better than the Qt doc that would be great as well.

Thanks much for any feedback.

Upvotes: 1

Views: 652

Answers (2)

Rustam Safin
Rustam Safin

Reputation: 842

Did you read about Model/View Programming?

http://doc.qt.io/qt-4.8/model-view-programming.html

Upvotes: 0

vahancho
vahancho

Reputation: 21248

As the function name hints the `QAbstractItemModel::data()' is for providing the information that should be visualized by the view. View doesn't need to cache all the data (in some cases thousands of elements) at once, but incrementally queries it from this function as soon as it should be shown on the screen.

When I talk about the data, I assume that it could be item's text, text color, background color, icon etc. All these types of data represented by Qt::ItemDataRole enum and the data itself represented by QVariant.

For example, if you have a tree view and corresponding model. When you scroll the tree down, it should paint, say 20 nodes. Tree view calls model's data() function for each of these 20 nodes to paint their texts, icons, backgrounds etc.

And finally, for better understanding roles. Instead of having textData(), colorData(), iconData() function in the model, Qt provides one single function data() with ability to conditionally chose which data to return depending on the role. This is much convenient design wise.

Upvotes: 1

Related Questions