Reputation: 97
I have followed this example with some changes to show QStringList in ListView. So, I have a QStringList
in MyClass.cpp and I want to show those items in ListView in MyDialog.qml
////main.cpp////
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
MyClass *strListView=new MyClass;
engine.rootContext()->setContextProperty("strListView", strListView);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
//// MyClass.h////
#include <QObject>
#include <QAbstractTableModel>
#include <QModelIndex>
#include <QHash>
#include <QVariant>
#include <QByteArray>
#include <QList>
#include <QDebug>
class MyClass: public QAbstractListModel
{
Q_OBJECT
public:
MyClass(QObject *parent=nullptr);
private:
QStringList str;
////MyClass.cpp////
MyClass::MyClass(QObject *parent)
: QAbstractListModel {parent}
{
str.append("name1");
str.append("name2");
str.append("name3");
QQuickView view;
QQmlContext *ctxt = view.rootContext();
ctxt->setContextProperty("strListView", QVariant::fromValue(str));
view.setSource(QUrl("qrc:MyDialog.qml"));
}
In qml I have 2 qml files: main.qml and MyDialog.qml ////MyDialog.qml////
...
Rectangle
{
id:recList
width:100
height:50
ListView
{
width: parent.width
height: parent.height
anchors.fill: parent
Text {
text: modelData
}
}
It doesnt show anything and I get the warning: ReferenceError: modelData is not defined.
Upvotes: 0
Views: 805
Reputation: 6084
I think that the usage inside your Qml Component should be somthing like this:
ListView {
model: myModel;
Text {
text: displayRole
}
}
Inside your C++ Component you should expose the model to the QML file:
QQmlContext *ctxt = view.rootContext();
ctxt->setContextProperty(myModel,this);
Finally, you need to map the Qt::ItemDataRole
by setting setRoleNames
on your model, like:
QHash<int, QByteArray> map={{Qt::ItemDataRole::DisplayRole, "displayRole"}};
this->setRoleNames(map);
I also think, that it is not really necessary to derive from QAbstractListModel
for such an easy use case. Just use QStandardItemModel
and you are home free.
Upvotes: 1