PDA

View Full Version : QStringListModel doesn’t show on QML ListView.



swagat
3rd September 2013, 01:41
Hi,
I’m pretty new to QML. I have defined QStringListModel in CPP and exposed to QML. My qml is not able to show list of strings that my model is set to. Please find my code as follows:


int main(int argc, char ** argv)
{
QGuiApplication app(argc, argv);


QQuickView view;
QQmlContext *ctxt = view.rootContext();

QStringListModel *model = new QStringListModel();
QStringList list;
list << "a" << "b" << "c"<<"s"<<"w";
model->setStringList(list);


ctxt->setContextProperty("myModel", model);


//![0]

view.setSource(QUrl("qrc:view.qml"));
view.show();
return app.exec();
}



import QtQuick 2.0
//![0]

ListView {
width: 100; height: 100

model: myModel
delegate: Rectangle {
height: 25
width: 100
Text { text: modelData }

}
}




Am missing something? Please suggest!

Added after 1 27 minutes:

I solved the problem by using role name as Qt::display in my qml file.

import QtQuick 2.0
//![0]

ListView {
width: 100; height: 100

model: myModel
delegate:
Item{
Rectangle {
height: 25
width: 100
Text { text: display }

}
}
}


QVariant QStringListModel::data(const QModelIndex &index, int role) implemented for Qt::DisplayRole only hence it was not able to show the items.


QVariant QStringListModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() >= lst.size())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole)
return lst.at(index.row());
return QVariant();
}


But with same I’m hit with another problem i.e. my qml shows only the lat item. Any idea how display the entire list?

wysota
3rd September 2013, 19:47
This works quite fine for me without touching QStringListModel:

import QtQuick 2.0

Rectangle {
width: 360
height: 360
ListView {
anchors.fill: parent
model: stringlistmodel
delegate: Text { text: display }
}
}

BTW. modelData didn't work for you because it works for QStringList based models (where you expose QStringList to QML) and not for QStringListModel (which is a QAbstractItemModel subclass).