QML bindings and scope



  • Hi all,

    So I'm thoroughly confused about how scope works in qml. Here's a little test:

    @
    import QtQuick 2.0

    Rectangle {
    width: 640/2
    height: 1136/2

    Item {
    width: parent.width
    height: parent.height

    Image {
    id: viewDummy
    anchors.fill: parent
    source: "viewDummy.png"

    ListModel {
    id: comments
    ListElement {
    modelData: "comment 1a"
    }
    ListElement {
    modelData: "comment 1b"
    }
    }
    }

    ListView {
    anchors.fill: parent

    model: viewDummy.comments

    delegate: Rectangle {
    height: 25
    width: 100
    Text { text: modelData }
    }
    }
    }
    }
    @

    The above does not display the contents of the model "comment 1a" and "comment 1b". However, if I change "viewDummy.comments" to just "comments" they are displayed..

    I would expect the reverse to be true... why can the ListView "see" the ListModel that's wrapped in the Image "viewDummy"? Does the nesting not affect scope?

    Thanks for any advice!

    Tyler


  • Moderators

    Within a single QML file, ids are just that: IDs. You don't need to specify the "parent" ID, they are sort of global (but, again: only within this QML file).

    By specifying parent.something, you can refer to properties of that parent, like parent.width.



  • IDs are global within a file?! That's a good one to have straight... thanks!



  • Hi,

    Actually, ids are unique within a component scope. In most cases, this means "within a file" (since a QML document is a QML type definition which can be instantiated via a component, and thus a given instantiation of the type has its own component scope), but there are some subtleties.

    See http://doc-snapshot.qt-project.org/qt5-stable/qtqml-syntax-objectattributes.html#the-id-attribute and http://doc-snapshot.qt-project.org/qt5-stable/qtqml-documents-scope.html for more information. Delegates are interesting, because they implicitly define a component scope.

    Cheers,
    Chris.


Log in to reply
 

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