PDA

View Full Version : Associate data with child items in listView



moiit
11th August 2011, 09:21
Hello folks,
I have spent hours of time on how to assign data to a child item in a listView.
What's wrong? Please help!


#include <QApplication>
#include <QtDebug>
#include <QtCore>
#include <QtGui>

int main(int argc, char** argv)
{
QApplication app(argc, argv);
QMainWindow window;

QSplitter *sp=new QSplitter;
QListView *listView1=new QListView;
QListView *listView2=new QListView;
sp->addWidget(listView1);
sp->addWidget(listView2);

QStandardItemModel model;

QStandardItem *group1 = new QStandardItem("Music Group 1");

QStandardItem *music1=new QStandardItem("Music 1");
music1->setData("Some datails", Qt::UserRole);
qDebug()<<model.data(model.index(0,0).child(0,0), Qt::UserRole);

group1->appendRow(music1);

model.appendRow(group1);

QStandardItem *group2 = new QStandardItem("Music Group 2");

QStandardItem *music2=new QStandardItem("Music 2");
qDebug()<<model.data(model.index(1,0).child(0,0), Qt::UserRole);

group2->appendRow(music2);

model.appendRow(group2);

listView1->setModel(&model);
listView1->setRootIndex(QModelIndex());
listView2->setModel(&model);

QObject::connect(listView1, SIGNAL(clicked(const QModelIndex&)),
listView2, SLOT(setRootIndex(const QModelIndex&)));

window.setCentralWidget(sp);
window.show();

return app.exec();
}


Result:

QVariant(, )
QVariant(, )

It seems that the parent items are showed fine, and the corresponding data are retrieved. But the child item & its data are invalid.

Any advice is grateful!

wysota
11th August 2011, 09:31
You didn't create any child items. You have a flat model with two rows and one column.

MarekR22
11th August 2011, 09:39
See examples how to build tree data model here (http://doc.qt.nokia.com/latest/qstandarditemmodel.html#details).
And:

model.index(0, 0).child(0,0);QModelIndex::child (http://doc.qt.nokia.com/latest/qmodelindex.html#child)

moiit
11th August 2011, 11:56
You didn't create any child items. You have a flat model with two rows and one column.

See examples how to build tree data model here (http://doc.qt.nokia.com/latest/qstandarditemmodel.html#details).
And:

model.index(0, 0).child(0,0);QModelIndex::child (http://doc.qt.nokia.com/latest/qmodelindex.html#child)

Thanks for advice!
I just edited the codes, please see in thread.
The child items can be showed in listView2, but still can not retrieve data from them.

Added after 22 minutes:

OK! Got it!

model.setData(model.index(1,0).child(0,0), "Some details", Qt::UserRole);
qDebug()<<model.data(model.index(1,0).child(0,0), Qt::UserRole);
this way, it works as expected.

A lot of thanks for you guys!