PDA

View Full Version : Populate a custom model



Str Anger
3rd June 2016, 15:48
Hi everyone !

I have navigated through the Internet all day to find an answer to my question, but it seems that the answer is too obvious to be posted on the web. So here it is :

How do I set custom items to my custom models ?

I have been on the Qt Doc page related to the QAbstracItemModel, and have no clue on which methods to call to let the model know I created new rows (tried beginInsertRows() / insertRow () / endInsertRows() but it did not seem to have any effect) and even if I would have succeeded, how will the model know that he has to check on my QList<MyCustomItem *> to populate himself (and create the QModelIndexes that I'll need to use afterwards).

I hope I have been clear enough on my questions (I could have linked my code, but it is quite long).

I thank you for any answer, and am sorry for my poor english.

anda_skoa
3rd June 2016, 16:09
Yes, beginInsertRows() and endInsertRows() make sure that any view using the model will know to update itself.

So you
1) call beginInsertRows()
2) modify your list
3) call endInsertRows()

Assuming of course you have implemented rowCount() to check the size of the list and data() to access the list.
And columnCount() in case this is a table model.

Which of the three base classes did you derive from?

Cheers,
_

Str Anger
6th June 2016, 09:20
Hi anda_skoa, and thank you for your answer.

I derived my model from QAbstractItemModel, but I do use it as a simple list at the moment (no columns defined atm).
I did what you said :

1. Reading my file (.txt file)
2. beginInsertRows()
3. while (!in.atEnd()) -> parsing my file with regexps and appending items in my list for each cases
4. endInsertRows()

Problem is : there actually are items in my list, but still the view displays nothing

I use a simple data() implementation :

if (role == Qt::DisplayRole)
return QString("Hello World");
return QVariant();

I also have implemented rowCount() as a simple return MyList.count();

Am I missing something, or doing something wrong (if you want the full code tell me)

Thank you

Added after 42 minutes:

Ok, I found what I did wrong :

In the index(int row, int column, QModelIndex &parent) method, I returned QModelIndex() instead of createIndex(row, column), so every item had the same "empy" QModelIndex.

So the problem is now solved. How do I close the thread ? (if it is my duty to do it)

anda_skoa
6th June 2016, 18:44
I derived my model from QAbstractItemModel, but I do use it as a simple list at the moment (no columns defined atm).

Then derive from QAbstractListModel as that limits the methods you need to implement to rowCount() and data().
You can easily rebase that later on QAbstractTableModel and then just add columnCount() and extend data().

Only derive from QAbstractItemModel if you really need a tree.
That then requires implementation of index() and parent(), which can be tricky.

Cheers,
_