Model for custom object
-
Hello,
I have been searching and reading documentation in earnest to figure out how to create a model (to be used in a table view) for a list of custom objects. My general scenario is this: assuming I have an QList of objects of a custom class, I would like to create a model which will allow these objects to be displayed in a table where each row is an object and each column is a member variable.
I have already implemented rowCount(), columnCount(), data(), and headerData() and am able to get data to be displayed in the table when I initially perform setModel() on the QTableView. My model doesn't hold the actual data but only a pointer to a QList. For example, my constructor is
PortModel(QList<AbstractPortInfo *> *infos);
The problem I am having is figuring out how to update the view when I append/remove/change objects in the List. I have read that you should emit dataChanged() which I am doing as follows
emit dataChanged(index(infos->length() - 1, 0), index(infos->length() - 1, 1)); //Assuming the AbstractPortInfo object has 2 members wish to return
when I append an item, however this does nothing.
I don't want to hold the data in the model itself because I am using the array of objects elsewhere in scenarios where I don't need a whole model.
Any ideas as to how this can be accmplished?
Thanks in advance! -
Hi,
How are you adding data to your list ?
How do you propagate that information to the upper layers? -
When I use the QList outside of the widget which has the QTableView (i.e. when I don't care about displaying the data), I simply use the append() method of the list. From within the widget with the view, I added an append() method as such
void append(AbstractPortInfo *info);
to the model so that I know when an update occurs to potentially tell the view to update.
-
You must inform the item model of any changes you make to your own model.
It should look something like this:void append(AbstractPortInfo *info) { beginInsertRows(QModelIndex(),infos->count(),infos->count()); infos->append(info); endInsertRows(); }
Look at the protected methods of QAbstractItemModel Class for more.
-
dataChanged
only notifies that the data contained in an existing item changed.
You need to use thebegin*()
/end*()
methods. unfortunately this makes:don't want to hold the data in the model itself.
difficult because those methods are protected and you need to add public methods (even slots) that call those private methods
-
You must inform the item model of any changes you make to your own model.
It should look something like this:void append(AbstractPortInfo *info) { beginInsertRows(QModelIndex(),infos->count(),infos->count()); infos->append(info); endInsertRows(); }
Look at the protected methods of QAbstractItemModel Class for more.
This works like a charm! I knew it couldn't be too difficult to achieve, I was just a bit confused.
Thank You!