rbtLong
rbtLong

Reputation: 1572

Binding to QListView

I'm trying to list the items from a QStringList to QML, but I keep getting an undefined error for the bindings.

Here is the C++ code:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));  

    QStringList lst;
    QString m("item 1");
    lst.append(m);

    QQmlComponent comp(&engine);
    QQmlContext *ctx = engine.rootContext();
    ctx->setContextProperty("pLst", QVariant::fromValue(lst));

    return app.exec();
}

Here is the QML code:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    id: root; objectName: "root"
    title: qsTr("Doesn't Matter")
    width: 640
    height: 480
    visible: true

    ListView{
        id: lst
        model: pLst
    }
}

The error says pLst is not defined.

Upvotes: 0

Views: 386

Answers (1)

Nikita Krupenko
Nikita Krupenko

Reputation: 1175

This is because you call load() before you set context property, so pLst does not yet exists at the moment ListView is constructing.

You should call load() after you set the context properties used for initialization of QML objects.

Upvotes: 2

Related Questions