I am trying to figure out the "best" way stylistically in Qt to implement a simple custom model. As a strawman example, suppose I want to display a read-only list of text items, some of which may be marked with an asterisk. I want to be able to change what's in the list and turn the asterisks on and off:
ABC
DEF*
GHI
I want my model or model item to store two properties, a string "text" and a bool "starred". The view displays the text and adds an asterisk if "starred" is true.
I can think of several ways to do this. I'd use a QListView for display.
1. Subclass QStringListModel and have it store the "starred" property in a user-defined role. Store the base text in the DisplayRole. Reimplement data() to check the user-defined role and add "*" to the text as necessary when the DisplayRole is requested.
2. Subclass QAbstractItemModel to store the properties in some private data structure and compute the displayRole value from those properties. Don't actually store anything in roles.
3. Use QStandardItemModel as is, without subclassing. Instead, subclass QStandardItem to store my properties and compute the displayRole value from those properties.
4. Have my own class that with appropriate set/get functions that store the state. When the state changes, my class will update the QStringListModel's text appropriately. So the QStringListModel ends up being a sort of "view" on the actual data.
In general I find the model classes presented by Qt to be fairly constrained. They don't map very well to my own idea of a model being some arbitrary data object. For a multivalued object, Qt lets you store the values as columns, or as roles, but both correspond closely to what a view wants, not how the actual data might be structured.
Any comments? Maybe all of these ways are just fine. Most of the questions I've found on subclassing models have to do with complicated tree or table models, but not basic questions about mapping existing data into models.
Thanks,
Dan
Bookmarks