Problem Accessing Views and Models from Delegates



  • Hi all,
    i have a problem when in a delegate i try to access data from the model or the view. I read the documentation at:

    http://qt-project.org/doc/qt-4.8/qdeclarativemodels.html#accessing-views-and-models-from-delegates

    I copied the following code in a new QML project and run in QtCreatore 2.4.1 with Qt 4.8:
    @import QtQuick 1.1

    Rectangle {
    width: 200; height: 200

    ListModel {
        id: fruitModel
        property string language: "en"
        ListElement {
            name: "Apple"
            cost: 2.45
        }
        ListElement {
            name: "Orange"
            cost: 3.25
        }
        ListElement {
            name: "Banana"
            cost: 1.95
        }
    }
    
    Component {
        id: fruitDelegate
        Row {
                Text { text: " Fruit: " + name; color: ListView.view.fruit_color }
                Text { text: " Cost: $" + cost }
                Text { text: " Language: " + ListView.view.model.language }
        }
    }
    
    ListView {
        property color fruit_color: "green"
        model: fruitModel
        delegate: fruitDelegate
        anchors.fill: parent
    }
    

    }@

    The qml viewer displays the list but i get the following error:

    bq. file:///[...].qml:28: TypeError: Result of expression 'ListView.view' [null] is not an object.
    file:///[...].qml:26: TypeError: Result of expression 'ListView.view' [null] is not an object.

    So, what i'm doing wrong?

    Thanks for you time



  • Not sure why, but I think you cannot access ListView directly from within the Text element, you have to give the Row an id, e.g. delegate, and access ListView as delegate.ListView. Or just use parent.ListView.



  • Yes, you can. You just have to let it know where the view is. Try this!
    @
    Component {
    id: fruitDelegate
    Row {
    id: wrapper
    Text {
    text: " Fruit: " + name
    color: wrapper.ListView.view.fruit_color
    }
    // ... etc
    }
    }
    @



  • Thanks to both of you, fast and precise help. Meanwhile i was searching how to signal the documentation problem i found this bug report:

    https://bugreports.qt-project.org/browse/QTBUG-22163

    Note to self: check bug reports also for documentation.


Log in to reply
 

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