Search code examples
androidqtlistviewqml

How to set value to a model from the property?


I want to add different files to the ListView model depending on the OS:

ApplicationWindow {
    id: window
    readonly property string settingsFile: (Qt.platform.os === "android") ? "qrc:/huts/qml/settings-android.qml" : "qrc:/huts/qml/settings.qml"
    Drawer {
        ListView {
            id: listView
            model: ListModel {
            ListElement { title: qsTr("Port Settings"); source: window.settingsFile }
            ListElement { title: qsTr("Terminal"); source: "qrc:/huts/qml/terminal.qml" }
            }
        ...
        }
    ...

But I get an error:

"ListElement: cannot use script for property value"

How can this goal be achieved?


Solution

  • For the Android part of your question, you should take the opportunity to use +android file selectors:

    huts/qml/terminal.qml
    huts/qml/+android/terminal.qml
    

    i.e. when you use "huts/qml/terminal.qml" in QML, QML will automatically load the Android specialized file on Android and load the other by default.

    As to your ListModel, QML does not permit you to initialize it using expressions, so accessing variables or using qsTr() both are not permitted declaratively. As suggested by the other answer you can do it in code. You can strike a higher balance between declarative and imperative, by declaring a JavaScript object and initialize your ListModel from the object, e.g.

        ListView {
            id: listView
            model: ListModel {
                property var _data: [
                    { title: qsTr("Port Settings"), source: "huts/qml/settings.qml" },
                    { title: qsTr("Terminal"), source: "huts/qml/terminal.qml" }
                ]
                Component.onCompleted: { for (let obj of _data) append(obj) }
            }
            delegate: ItemDelegate { text: title }
        }
    

    N.B. the use of "qrc:/" in your QML may not be necessary, since your main application is probably a "qrc:" resource already, so, it is enough to use a relative reference to where your main file is. So "huts/qml/settings.qml" instead of "qrc:/huts/qml/settings.qml"

    References: