Set context property from QML



  • Hi, I would like to set some context properties for an object when I create it. Like for ListView or Gridview, I would like to have a model property available to the delegates.
    Something like :

    // MyObject.qml
    Row {
        property var items
        Repeater {
            model : items
            Delegate {
                // This line is wrong and only here to get the idea
                setContextProperty( "model", items.get(index) )
            }
        }
    }
    
    // Delegate.qml
    Rectangle {
        width: model.width
        height: model.height
    }
    

    I know I can define a property model in the Delegate but I would prefer not to do so and stick with the way basic views works (with the variable model as a context property).
    Can some help me on how to declare such variables from QML ?
    Thx, MoaMoaK


  • Moderators

    @MoaMoaK said in Set context property from QML:

    I know I can define a property model in the Delegate but I would prefer not to do so and stick with the way basic views works (with the variable model as a context property).
    Can some help me on how to declare such variables from QML ?

    Even though in my opinion this is the dirty way to pollute the context property space...

    You need to go around C++ to alter the qml context. So you could add a generic context property (QObject) which offers a method to add new context properties.
    But anyway you need to change your coding, since the context properties are then added later then before. This needs to be considered in your QML design!

    Edit:
    a method which might help you is

    #include <QtQml>
    
    QQmlContext * context = qmlContext(anyObjectComingFromQml);
    context->setContextProperty(name, value);
    


  • Sorry, I'm a bit late for the answer, but I found a way to do it fully in QML using Loaders (might works with other kind of items, I haven't tried) and so I can close this topic :

    // MyObject.qml
    Row {
        property var items
        property Component delegate
        Repeater {
            model : items
            Loader {
                sourceComponent : delegate
                // The line to add variables
                property var model : items.get(index)
            }
        }
    }
    
    // Delegate.qml
    Rectangle {
        // model does exists here
        width: model.width
        height: model.height
    }
    

Log in to reply
 

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