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();
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();
}
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();
}
To copy to clipboard, switch view to plain text mode
import QtQuick 2.0
//![0]
ListView {
width: 100; height: 100
model: myModel
delegate: Rectangle {
height: 25
width: 100
Text { text: modelData }
}
}
import QtQuick 2.0
//![0]
ListView {
width: 100; height: 100
model: myModel
delegate: Rectangle {
height: 25
width: 100
Text { text: modelData }
}
}
To copy to clipboard, switch view to plain text mode
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 }
}
}
}
import QtQuick 2.0
//![0]
ListView {
width: 100; height: 100
model: myModel
delegate:
Item{
Rectangle {
height: 25
width: 100
Text { text: display }
}
}
}
To copy to clipboard, switch view to plain text mode
QVariant QStringListModel::data(const QModelIndex &index, int role) implemented for Qt:isplayRole only hence it was not able to show the items.
{
if (index.row() < 0 || index.row() >= lst.size())
if (role == Qt::DisplayRole || role == Qt::EditRole)
return lst.at(index.row());
}
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();
}
To copy to clipboard, switch view to plain text mode
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?
Bookmarks