Reputation: 143
I have subclassed a QTableModel and the data I want to be displayed is the contents of an std::vector which I keep a reference to in my model. I have subclassed a QTableView to represent MyClass objects and display different properties of MyClass objects in different columns. Initially, I get exactly what I want to be displayed: the initialized std::vector and the 10 elements I put into it are displayed. What I want to do after is add elements by means of other widgets to the std::vector and update the model and view accordingly. So I must somehow notify the model of the change and from what I have gathered from reading similar questions and Qt examples, it should be done like this: Before adding elements to the std::vector, I must first notify the model that I'm going to insert some rows. So what I did was create a member function in my model class that basically does this:
beginInsertRows(QModelIndex(), lastdisplayedrow, lastdisplayedrow+1);
myvector.push_back(myclassobject);
endInsertRows();
Since I didn't get the new element displayed, I decided that I also need to do something like this:
emit dataChanged(args_that_represent_the_new_row);
However, I can't get that new MyClass object to be displayed. And whatever the arguments in beginInsertRows, the new row is always appended at the end. What I mean by that is I can't get a new row in-between the already displayed rows even when I pass arguments like
beginInsertRows(QModelIndex(), 0, 1);
Any ideas on what I am doing wrong? Thank you king_nak for noticing the error, unfortunately the error was in my question and not my code. lastdisplayedrow is indeed the size of my vector. My remaining question is (I leave room for the possibility that my approach is right I just messed up something in my code): - Is this the correct approach to dealing with data that is stored outside the model?
For anyone wondering: This seems like the correct approach to do this as I just managed to make it work. I'm going to give credit to king_nak for essentially finding what's wrong with the little snippet I provided. As for the real source of my problem: it was a dumb mistake on my part: when overriding rowCount I simply returned the value of my nRow member which had only been initialized in the constructor with myvector.size().
Upvotes: 3
Views: 1176
Reputation: 11513
The call to beginInsertRows
seems to be incorrect:
beginInsertRows(QModelIndex(), lastdisplayedrow, 1);
This means you will insert rows in the span [lastdisplayedrow
, 1
]. The parameters in this function specify the start- and end-index of the to be inserted rows (see QAbstractItemModel::beginInsertRows). Your call should look like this:
beginInsertRows(QModelIndex(), lastdisplayedrow, lastdisplayedrow + 1);
assuming that lastdisplayedrow
equals your vector's size.
Upvotes: 2