PDA

View Full Version : Reading items in a QStandardItemModel



janorcutt
11th February 2010, 10:44
ok i may be being thick here but i have a problem.
i subclassed QStandardItemModel for my app, and have set up a model with 4 columns. when i read a list of items from a file it adds the rows in arraying the items in the correct order. that is File, Title, Artist, Album. now when i double click on the treeview it calls the following code


void myTunes::treeDclick(QModelIndex index)
{
QString str(model->fileForIndex(index));
Phonon::MediaSource src(str);
mediaObject->stop();
mediaObject->setCurrentSource(src);
mediaObject->play();
}


QString mediaLibrary::fileForIndex(QModelIndex index)
{
int i;
i = index.row();
return QString(item(i,0)->text());
}

when compiled the programme runs fine untill the double click event when the code
return QString(item(i,0)->text()); creates an error and the debugger halts the programme execution. so my question is why??? and how do i get around it???

as there are no errors shown i cant post them. any help would be very much appreciated.

ta janorcutt :confused:

faldzip
11th February 2010, 11:00
first of all you can get your string directly from QModelIndex:


index.data(Qt::DisplayRole).toString();

if it is in the column 0. If not then:


index = index.model()->index(index.row(), 0, index.parent());

should work I think.

Second of all: is your model a tree structure? If yes then you forgot about parents. item(i, 0) gives you top level item in row i and column 0. So when you have some child nodes it will work incorrectly when clicking child node, because it will try to get text from top level item in the same row as your clicked child item.

Third of all: item(i, 0)->text() already return QString so no need to construct QString copy which would be copied and destructed in the next line, so it should be:


return item(i, 0)->text();


Fourth of all: it is good to check first if pointer returned by item(i. 0) is valid. For example in your "parents case" item at row i and column 0 may not exist so item() will return 0. Using ->text() on null pointer gives you what? That's right: Segmentation fault! :]

janorcutt
11th February 2010, 11:45
aahhh, thanks it works now. my model is actually a table but i suppose you still need to tell qt exactly where to look in relation to the index passed.

like so


QString mediaLibrary::fileForIndex(QModelIndex index)
{
int i;
i = index.row();
QModelIndex ind(index.model()->index(i,0,index.parent()));

return ind.data(Qt::DisplayRole).toString();
}

also i've hidden the 1st column '0' in the tree so i needed to reference it in relation to the index passed by the event...

thanks again

janorcutt :D

faldzip
11th February 2010, 13:24
And when you are not sure that the given index will be always valid then remember to check is with:


if (!index.isValid()) {
// not valid! do sth, e.g. return;
}