How do I reference or link a model from another qml file in my listview?



  • I'm a fairly new Qt/QML user, and I'm frustrated by my inability to follow a handful of code examples.

    The code examples create separate qml files for models, views, and delegates and then link them together as appropriate by referring to them by name with {} (like an object) in the listview.

    For instance,

    [MyModel.qml]

    ListModel {
       ListItem {
            name:  "Brandon"
            age:  "16"
       }
    }
    

    [ListView.qml]

    ListView {
         width:  500
         height: 500
         model:  MyModel {}
         delegate:  MyDelegate {}
    }
    

    This is very simplified, but when I try to run something like this in QtCreator, I get one of the following two errors: (1) "expected error" or (2) ReferenceError: MyModel is not defined.

    If I put everything in one file, it runs perfectly, but I want to be able to reference model objects in different files for organizational reasons.

    Anyway, I think there must be something simple I'm overlooking, but I've tried everything. Thanks in advance.



  • Hi @Brandon-Martin ,

    Your code doesn't have a problem but I don't know ListItem component exist.
    I change the component to ListElement.
    I think you missed something so please check below.

    1. file position(in same folder)
    2. file name (MyModel.qml : case sensitive)
    3. add import QtQuick x.x
    • you can move file position and naming case insensitive using qmldir file (doc-qmldir)

    I attached my test code.

    ListView.qml

    import QtQuick 1.0
    
    Item {
        id: main
        width: 1280; height: 720
        focus: true
    
        ListView {
            id: list
            width: 100; height: 100*4
            focus: true
            clip: true
            model: MyModel {}
            delegate: Rectangle {
                width: 100; height: 100
                color: "black"
                Text {
                    text: index
                    color: "white"
                    anchors.centerIn: parent
                }
            }
        }
    }
    

    MyModel.qml

    import QtQuick 1.0
    
    ListModel {
        ListElement { name: "test1" }
        ListElement { name: "test2" }
        ListElement { name: "test3" }
    }
    


  • Thank you, Jean! You were correct. My error was a case-sensitivity thing. I'm a little embarrassed, but appreciative of your help.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.