PDA

View Full Version : How many times is the data() function in QStandardItemModel been invoked?



keithlee980
16th January 2014, 06:41
Hi all:
i create a 2*2 table, and i create my own simple model, just re-implementing the data() function. The code is as follows:


QVariant MyStandardItemModel::data(
const QModelIndex & index,
int role) const
{

int column=index.column();
qDebug()<<"row="<<index.row()<<"column="<<index.column()<<"data role="<<role;
if(role==Qt::DisplayRole){
//qDebug()<<"row="<<index.row()<<"column="<<index.column()<<"display="<<role;
return column+3;
}
else return QStandardItemModel::data(index,role);
}


when i run my program , i think the data() function should be called 4 times, but actually it is called many times,
9933
It is confused me.
My questions are:
1.why the data() function is called so many times but not 4 times?
2.why the item has 7 roles while i don't set roles to item. For example:
row= 0 column= 0 data role= 6
row= 0 column= 0 data role= 7
row= 0 column= 0 data role= 9
row= 0 column= 0 data role= 10
row= 0 column= 0 data role= 1
row= 0 column= 0 data role= 0
row= 0 column= 0 data role= 8
Is this the default setting or i missing something?

ChrisW67
16th January 2014, 06:49
It is called to get data for cell in each role that it requires to construct the view. There are roles for check states, icons, colours, alignment, tool tips, status tip, size hint etc. Your subclass simply passes these off to the QStandardItemModel, which returns the data it has for these roles.

wysota
16th January 2014, 06:50
Why would it be called 4 times? The model is being asked for all roles the view needs so for each item the function is called several times, as in your log. The view does not "see" your C++ code, it does not know you did not set any other roles than the display role so it asks for other roles used by the view or the delegate as well.

keithlee980
16th January 2014, 09:04
Thank you very much

anda_skoa
16th January 2014, 09:29
You can think of that as a conversation between to people, where one can do a lot of things and the other decides which of those matter.

The view knows how to do stuff and asks the model if it wants to provide any input on those matters:

View: Hi there, what do you want me to draw in cell 0/0?
Model: (column+3 -> 3) 3!
View: Right. Any specific font I should use?
Model: No
View: Ok, will use the standard font. Any wishes regarding the text color?
Model: No
View: Excellent, I hate it when models mess up the colors. Just in case, does this cell have a check state, i.e. do you want me to draw a checkbox?
.....

View: All right! Lets move on to cell 0/1....

Cheers,
_